Dependency Injection with ASP.NET Web API

后端 未结 1 1385
生来不讨喜
生来不讨喜 2021-01-24 04:51

I am trying to use DI in my ASP.NET Web API Controller. Apparently there are a few implementations out there. I was just wondering which of these (Castle, Ninject, unity etc.) w

1条回答
  •  野的像风
    2021-01-24 05:51

    You don't need a DI Container for this. Here's how to do it by hand:

    public class PoorMansCompositionRoot : IHttpControllerActivator
    {
        public IHttpController Create(
            HttpRequestMessage request,
            HttpControllerDescriptor controllerDescriptor,
            Type controllerType)
        {
            if (controllerType == typeof(ImportJsonController))
                return new ImportJsonController(new MyFilter());
    
            return null;
        }
    }
    

    You need to tell ASP.NET Web API about this class (e.g. in your Global.asax):

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

    You can read about all the details here: http://blog.ploeh.dk/2012/09/28/DependencyInjectionandLifetimeManagementwithASP.NETWebAPI

    0 讨论(0)
提交回复
热议问题