How to create dependency injection for ASP.NET MVC 5?

前端 未结 9 1736
挽巷
挽巷 2020-12-23 03:08

Creating Dependency Injection with ASP.NET Core is fairly easy. The documentation explains it very well here and this guy has a killer video to explain it.

However,

9条回答
  •  粉色の甜心
    2020-12-23 03:46

    I recommend using Windsor, by installing the nuget package Castle Windsor MVC Bootstrapper, then you can create a service that implements IWindsorInstaller, something like this:

    public class ServiceRegister : IWindsorInstaller
    {
        public void Install(Castle.Windsor.IWindsorContainer container,
        Castle.MicroKernel.SubSystems.Configuration.IConfigurationStore store)
        {
            SomeTypeRequiredByConstructor context = new SomeTypeRequiredByConstructor ();
    
            container.Register(
                Component
                    .For()
                    .ImplementedBy().
                 DependsOn(Dependency.OnValue(context))//This is in case your service has parametrize constructoe
                    .LifestyleTransient());
        }
    }
    

    Then inside your controller something like this:

    public class MyController 
    {
        IServiceToRegister _serviceToRegister;
    
        public MyController (IServiceToRegister serviceToRegister)
        {
            _serviceToRegister = serviceToRegister;//Then you can use it inside your controller
        }
    }
    

    And by default the library will handle sending the right service to your controller by calling the install() of ServiceRegister at start up because it implements IWindsorInstaller

提交回复
热议问题