Does Simple Injector supports MVC 4 ASP.NET Web API?

后端 未结 2 682
温柔的废话
温柔的废话 2020-12-16 13:08

I am new to Simple Injector IOC container. I will start working in a project which will require a Multi-tenant ASP.NET MVC implementation using MVC 4 ASP.NET Web API.

<
2条回答
  •  不思量自难忘°
    2020-12-16 13:45

    The short answer is: yes, it works. Below is the code snippet that works for my project with both Web API and MVC4 controllers (partially based on Steven's response above):

    var container = new Container();
    
    //Register you types in container here
    
    container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
    container.RegisterMvcAttributeFilterProvider();
    
    var controllerTypes =
    from type in Assembly.GetExecutingAssembly().GetExportedTypes()
    where typeof(ApiController).IsAssignableFrom(type)
    where !type.IsAbstract
    where !type.IsGenericTypeDefinition
    where type.Name.EndsWith("Controller", StringComparison.Ordinal)
    select type;
    
    foreach (var controllerType in controllerTypes)
    {
        container.Register(controllerType);
    }
    
    container.Verify();
    DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
    

    To access your types in the API controllers you could use the following code snippet:

    DependencyResolver.Current.GetService()
    

提交回复
热议问题