简体   繁体   中英

Simple Injector in Web.MVC, injection not occuring

I am using Simple Injector for the first time. Nuget the MVC QuickStart version. In SimpleInjectorInializer.cs this gets called.

public static class SimpleInjectorInitializer
{
 /// <summary>Initialize the container and register it as MVC3 Dependency Resolver.</summary>
   public static void Initialize()
   {
      // Did you know the container can diagnose your configuration? 
     // Go to: https://simpleinjector.org/diagnostics
     var container = new Container();

     InitializeContainer(container);    
                container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

            container.Verify();

      DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
  }

  private static void InitializeContainer(Container container)
  {                 
   // For instance:
   container.Register<IQueryProcessor, QueryProcessor>(Lifestyle.Singleton);
   container.RegisterInitializer<WebApiController>(
                p=> p.QueryProcessor = container.GetInstance<IQueryProcessor>());
   }

WebApiController.cs. Injection doesn't happen. 

public class WebApiController : ApiController
{

 public IQueryProcessor QueryProcessor { get; set; }

 public WebApiController(IQueryProcessor queryProcessor)
 {

   QueryProcessor = queryProcessor;

 }

MVC Controllers are NOT the same thing as WebAPI controllers prior to ASP.NET5 (MVC 6) since MVC Controllers implement the IController interface and Web API controllers implement the IHttpController interface.

Simple Injector makes it very easy to override the default IHttpController instantiation, per their documentation .

using System.Web.Http;
using SimpleInjector;
using SimpleInjector.Integration.WebApi;

// This is the Application_Start event from the Global.asax file.
protected void Application_Start() {
    // Create the container as usual.
    var container = new Container();

    // Register your types, for instance using the RegisterWebApiRequest
    // extension from the integration package:
    container.RegisterWebApiRequest<IUserRepository, SqlUserRepository>();

    // This is an extension method from the integration package.
    container.RegisterWebApiControllers(GlobalConfiguration.Configuration);

    container.Verify();

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

    // Here your usual Web API configuration stuff.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM