Umbraco API控制器 - 从DI容器中解析

时间:2017-02-06 17:16:08

标签: asp.net-web-api2 owin autofac umbraco7

我试图让Umbraco与Autofac很好地配合,以便通过容器解析我的API控制器,并且我可以添加构造函数依赖项。

每当我尝试访问API控制器时,我都会从默认控制器激活器中收到错误:

  

尝试创建类型的控制器时发生错误   ' MigrateUsersController&#39 ;.确保控制器有一个   无参数公共构造函数。

但我不想使用默认激活器 - 我想从Autofac解析控制器。这就是我的主题:

public static void Configure(IAppBuilder app)
{
    var builder = new ContainerBuilder();

    //register all controllers found in this assembly
    builder.RegisterControllers(typeof(IocConfig).Assembly);
    builder.RegisterApiControllers(typeof(IocConfig).Assembly);

    builder.RegisterControllers(typeof(Umbraco.Web.UmbracoApplication).Assembly);
    builder.RegisterApiControllers(typeof(Umbraco.Web.UmbracoApplication).Assembly);

    builder.RegisterModule(new ServiceRegistrar());

    container = builder.Build();
    app.UseAutofacMiddleware(container);

    DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
    GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}

任何人都知道我在这里失踪了吗?

1 个答案:

答案 0 :(得分:0)

我在这里找到答案: http://24days.in/umbraco-cms/2015/integrating-an-application-into-umbraco-(using-ninject)/

我错过了这个:

GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), new UmbracoWebApiHttpControllerActivator(kernel));

以下是我对自定义激活器的实现:

public class UmbracoWebApiControllerActivator : IHttpControllerActivator
{
    private readonly DefaultHttpControllerActivator _defaultHttpControllerActivator;
    private readonly IContainer _container;

    public UmbracoWebApiControllerActivator(IContainer container)
    {
        this._defaultHttpControllerActivator = new DefaultHttpControllerActivator();
        this._container = container;
    }

    public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
    {
        object instance = null;
        if (_container.TryResolve(controllerType, out instance))
        {
            if (instance is IHttpController)
                return (IHttpController)instance;
        }

        IHttpController controller  =
            this.IsUmbracoController(controllerType)
                ? Activator.CreateInstance(controllerType) as IHttpController
                : this._defaultHttpControllerActivator.Create(request, controllerDescriptor, controllerType);

        return controller;
    }

    private bool IsUmbracoController(Type controllerType)
    {
        return controllerType.Namespace != null
            && controllerType.Namespace.StartsWith("umbraco", StringComparison.InvariantCultureIgnoreCase);
    }
}