MEF and WEB API 2.2



我正在尝试将依赖项注入到WebApi控制器中。

我创建了一个自己的IHttpControllerActivator类,并替换了globalConfiguration中的默认类。

 public class SimpleASPWebAPIContainer : IHttpControllerActivator
{
    private readonly CompositionContainer container;
    public SimpleASPWebAPIContainer(CompositionContainer compositionContainer)
    {
        container = compositionContainer;
    }
    public IHttpController Create(System.Net.Http.HttpRequestMessage request, System.Web.Http.Controllers.HttpControllerDescriptor controllerDescriptor, Type controllerType)
    {
        if (controllerType != null)
        {
            var export = container.GetExports(controllerType, null, null).FirstOrDefault();
            IHttpController result = null;
            if (null != export)
            {
                result = export.Value as IHttpController;
            }
            else
            {
                //result = base.GetControllerInstance(requestContext, controllerType);
                //container.ComposeParts(result);
            }
            return result;
        }
        else
        {
            return null;
        }
    }

    public void Dispose()
    {
        if (container != null)
            container.Dispose();
    }
}
var apiSimpleContainer = new SimpleASPWebAPIContainer(container);
        System.Web.Http.GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerActivator), apiSimpleContainer);

但是,当客户端应用程序调用控制器方法时,不会调用IHttpControllerActivation Create方法。

有人能帮我吗?

这是一个非常愚蠢的错误。
public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();
        ConfigureOAuth(app);
        MefConfig.RegisterMef(config);
        WebApiConfig.Register(config);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(config);

        AutoMapperConfig.InitAutoMapper();
    }

我应该使用新的HttoConfiguration实例来替换默认的IHttpControllerActivator,而不是System.Web.Http.GlobalConfiguration.Configuration.

最新更新