首页 > 解决方案 > 带有 Sitecore 和 WebApi 控制器的 SimpleInjector 没有默认构造函数

问题描述

我们在Helix项目中集成了 SimpleInjector ( 4.4.x) 。Sitecore 8.2

我们的基础层中有一个依赖注入项目,它由以下管道组成:

public void Process(PipelineArgs args)
{
    var container = new Container();
    container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

    // register app dependencies (omitted for readability)

    // get assemblies of our application
    container.RegisterMvcControllers(assemblies);
    container.RegisterWebApiControllers(GlobalConfiguration.Configuration,assemblies);

    container.Verify();

    DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
    GlobalConfiguration.Configuration.DependencyResolver =
        new SimpleInjectorWebApiDependencyResolver(container);
}

同样如本文所述,流水线处理器在 Sitecoreinitialize流水线中实现:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <initializeDependencyInjection/>
      <initialize>
        <processor type="Company.Foundation.Example.DependencyInjectionProcessor, Company.Foundation.Example"
                   patch:before="processor[@type='Sitecore.Mvc.Pipelines.Loader.InitializeControllerFactory, Sitecore.Mvc']" />
      </initialize>
    </pipelines>
  </sitecore>
</configuration>

如您所见,ASP.NET MVCWebApi都使用 ( .NET 4.6)。我们的解决方案仅包含 MVC 控制器。我们正在努力实现的是WebApi在我们的解决方案中引入。添加以下控制器时,一切正常:

public class HelloController : ApiController
{
    [HttpGet, Route("api/hello")]
    public IHttpActionResult Get()
    {
        return Ok("Hello World!");
    }
}

但是当我添加一个依赖项(并注册)时,例如:

public interface IFoo
{
    string Hello { get; }
}

public class Foo : IFoo
{
    public string Hello => "Hello World!";
}

public class HelloController : ApiController
{
    private readonly IFoo _foo;

    public HelloController(IFoo foo)
    {
        _foo = foo;
    }

    [HttpGet, Route("api/hello")]
    public IHttpActionResult Get()
    {
        return Ok(_foo.Hello);
    }
}

执行 HTTP 请求时,我在运行时收到以下异常消息:

System.InvalidOperationException:尝试创建类型为“HelloController”的控制器时发生错误。确保控制器有一个无参数的公共构造函数。

堆栈跟踪:

at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__15.MoveNext()

内部异常:

System.ArgumentException:类型“Company.Feature.Example.HelloController”没有默认构造函数

at System.Linq.Expressions.Expression.New(Type type)
at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)

让我感到奇怪的是它container.Verify()不会引发任何异常或警告。调试的时候可以看到HelloController注册Root Registrationscontainer.

此外,在根项目WebApi中设置了绑定重定向:web.config

<dependentAssembly>
  <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" xmlns="urn:schemas-microsoft-com:asm.v1" />
  <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" xmlns="urn:schemas-microsoft-com:asm.v1" />
</dependentAssembly>

标签: c#asp.net-mvcasp.net-web-apisitecoresimple-injector

解决方案


根据这个答案Steven在评论中建议的那样,依赖解析器稍后在 Sitecore 管道中被覆盖。

我已经扩展了initialize管道:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <initializeDependencyInjection/>
      <initialize>
        <processor type="Company.Foundation.Example.DependencyInjectionProcessor, Company.Foundation.Example"
                   patch:before="processor[@type='Sitecore.Mvc.Pipelines.Loader.InitializeControllerFactory, Sitecore.Mvc']" />
        <processor type=" Company.Foundation.Example.WebApiDependenceResolverProcessor, Company.Foundation.Example"
                   patch:after="*[@type='Sitecore.PathAnalyzer.Services.Pipelines.Initialize.WebApiInitializer, Sitecore.PathAnalyzer.Services']" />
      </initialize>
    </pipelines>
  </sitecore>
</configuration>

我还添加了以下处理器:

public class WebApiDependenceResolverProcessor
{
    public void Process(PipelineArgs args)
    {
        // retrieve container here

        GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);
    }
}

在这里,我们设置了Sitecore 重置WebApi 后的依赖解析器。


推荐阅读