Dependency Injection in .NET with examples?

前端 未结 8 1500
别跟我提以往
别跟我提以往 2020-11-27 14:31

Can someone explain dependency injection with a basic .NET example and provide a few links to .NET resources to extend on

8条回答
  •  孤城傲影
    2020-11-27 15:09

    Install below Nuget packages in main mvc4 project name SampleDependency. Unity.mvc4, unity.webapi and MicrosoftAsp.Net Web API 2.2 Web host

    In web project

    public static class Bootstrapper
    {
        public static IUnityContainer Initialise()
        {
            var container = BuildUnityContainer();
    
            DependencyResolver.SetResolver(new UnityDependencyResolver(container));
            GlobalConfiguration.Configuration.DependencyResolver = new Unity.WebApi.UnityDependencyResolver(container);
    
            return container;
        }
    
        private static IUnityContainer BuildUnityContainer()
        {
            var container = new UnityContainer();
    
            // register all your components with the container here
            // it is NOT necessary to register your controllers
    
            // e.g. container.RegisterType();
            container.RegisterType();
            container.RegisterType();
    
            RegisterTypes(container);
    
            return container;
        }
        public static void RegisterTypes(IUnityContainer container)
        {
    
        }
    }
    

提交回复
热议问题