Web.MVC中的简单注射器,注射未发生

时间:2015-05-21 17:22:12

标签: c# asp.net-mvc simple-injector

我第一次使用Simple Injector。 Nuget MVC QuickStart版本。在SimpleInjectorInializer.cs中,这将被调用。

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;

 }

1 个答案:

答案 0 :(得分:5)

MVC控制器与ASP.NET5(MVC 6)之前的WebAPI控制器不同,因为MVC控制器实现了IController接口,而Web API控制器实现了IHttpController接口。

Simple Injector可以很容易地根据documentation覆盖默认的IHttpController实例。

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.
}