Simple Injector 와 MVC 4 를 통합 하여 웹 Api 와 통합 하고 속성 을 통 해 프 리 젠 테 이 션 을 주입 합 니 다.

10801 단어 inject
1, MVC 와 통합
만 나 서 http://simpleinjector.codeplex.com/wikipage?title=Integration%20Guide&referringTitle=Home 저희 가 직접 MVC 4 프로젝트 테스트 를 해 보도 록 하 겠 습 니 다.
1.1 nuget
Mvc 의 통합 만 설치 하면 됩 니 다. 다른 의존 도 는 자동 으로 설 치 됩 니 다.
Install-Package SimpleInjector.Integration.Web.Mvc
1.2 Global.asax:
protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            
            //       
            // 1. Create a new Simple Injector container
            var container = new Container();

            // 2. Configure the container (register)
            //container.Register<IUserService, UserService>(Lifestyle.Transient);
            //container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Singleton);
            //        ,       ,Lifestyle        
            container.Register<Iaaa, aaa>(Lifestyle.Transient);

            // 3. Optionally verify the container's configuration.
            container.Verify();

            // 4. Store the container for use by Page classes.
            //WebApiApplication.Container = container;
            System.Web.Mvc.DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));

            // 5. register global filters //                 ,         
            //RegisterGlobalFilters(GlobalFilters.Filters, container);
        }

        //public static void RegisterGlobalFilters(GlobalFilterCollection filters, Container container)
        //{
        //}
    }

 
1.3 테스트 인터페이스 와 방법의 실현
    public interface Iaaa
    {
        int a { get; set; }
        string hello(string str);
    }

    public class aaa : Iaaa
    {
        public aaa()
        {
            a = DateTime.Now.Millisecond;
        }
        public int a { get; set; }

        public string hello(string str)
        {
            return "hello " + str + " timestamp: " + a;
        }
    }

1.4 컨트롤 러 에서 테스트
개인 변수 와 구조 함수 의 사용 에 주의 하면 됩 니 다.
    public class testController : Controller
    {
        private Iaaa _srv;

        public testController(Iaaa srv)
        {
            _srv = srv;
        }
        public string Index(string id)
        {
            return _srv.hello(id);
        }
    }

"hello my name timestamp 234" 를 올 바 르 게 출력 하 는 것 은 홈 페이지 와 똑 같 습 니 다. http://simpleinjector.codeplex.com/
2, WebApi 와 통합
http://simpleinjector.codeplex.com/wikipage?title=Web%20API%20Integration&referringTitle=Integration%20Guide 같은 항목 에서 테스트 하면 됩 니 다. 뮤 직 비디오 c 와 웹 api 통합 의 차 이 를 잘 보 여 줍 니 다. 따라서 새 항목 과 인용 을 추가 할 필요 가 없습니다.
 
2.1 웹 api 컨트롤 러 tst 새로 만 들 기
기본적으로 test 컨트롤 러 의 코드 를 복사 합 니 다. 간단 합 니 다.
    public class tstController : ApiController
    {
        private Iaaa _srv;
        public tstController(Iaaa srv)
        {
            _srv = srv;
        }
        public string get(string id)
        {
            return _srv.hello(id);
        }
    }

2.2 테스트 실패
/ api / tst / aaa 에 접근 하 였 으 나 Type 'WebApplication 1. Controllers. tst Controller' does not have a default constructor 를 잘못 보고 하 였 습 니 다. 위 에서 제공 한 홈 페이지 의 통합 설명 에 따라 Global. aax 를 변경 하면 됩 니 다. 다음 과 같이 고 칠 수 있 습 니 다 (수정 점 1 과 2 참조)
protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            
            //       
            // 1. Create a new Simple Injector container
            var container = new Container();

            // a.1 webapi, frist register controller    1
            var services = GlobalConfiguration.Configuration.Services;
            var controllerTypes = services.GetHttpControllerTypeResolver()
                .GetControllerTypes(services.GetAssembliesResolver());

            // register Web API controllers (important! http://bit.ly/1aMbBW0)
            foreach (var controllerType in controllerTypes)
            {
                container.Register(controllerType);
            }

            // 2. Configure the container (register)
            //container.Register<IUserService, UserService>(Lifestyle.Transient);
            //container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Singleton);
            //        ,       ,Lifestyle        
            container.Register<Iaaa, aaa>(Lifestyle.Transient);

            // 3. Optionally verify the container's configuration.
            container.Verify();

            // 4. Store the container for use by Page classes.
            //WebApiApplication.Container = container;
            System.Web.Mvc.DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
            
            // a.2 webapi      ,  verify()      2
            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);

            // 5. register global filters //                 ,         
            //RegisterGlobalFilters(GlobalFilters.Filters, container);
        }

        //public static void RegisterGlobalFilters(GlobalFilterCollection filters, Container container)
        //{
        //}
    }

재 테스트 통과 입 니 다.
3, 속성 을 통 해 주입
위 에서 보 여 준 것 은 모두 구조 기 를 통 해 주입 되 었 습 니 다. 속성 주입 에 관 해 Simple Injector 는 엄격 한 제한 을 했 지만 지원 합 니 다. 명시 적 주입 이 필요 합 니 다. http://simpleinjector.codeplex.com/wikipage?title=Advanced-scenarios&referringTitle=Home#Property-Injection 가장 간단 한 방법 을 직접 보 여 주 십시오.
container.RegisterInitializer<HandlerBase>(handlerToInitialize => {
    handlerToInitialize.ExecuteAsynchronously = true;
});

그래서 완 성 된 Global. sax 는 다음 과 같 습 니 다.
 protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            
            //       
            // 1. Create a new Simple Injector container
            var container = new Container();

            // a.1 webapi, frist register controller    1
            var services = GlobalConfiguration.Configuration.Services;
            var controllerTypes = services.GetHttpControllerTypeResolver()
                .GetControllerTypes(services.GetAssembliesResolver());

            // register Web API controllers (important! http://bit.ly/1aMbBW0)
            foreach (var controllerType in controllerTypes)
            {
                container.Register(controllerType);
            }

            // 2. Configure the container (register)
            //container.Register<IUserService, UserService>(Lifestyle.Transient);
            //container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Singleton);
            //        ,       ,Lifestyle        
            container.Register<Iaaa, aaa>(Lifestyle.Transient);
            container.RegisterInitializer<tstController>(c => c.s2 = new bbb());//  ,        

            // 3. Optionally verify the container's configuration.
            container.Verify();

            // 4. Store the container for use by Page classes.
            //WebApiApplication.Container = container;
            System.Web.Mvc.DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
            
            // a.2 webapi    2,    ,  verify()  
            GlobalConfiguration.Configuration.DependencyResolver = new SimpleInjectorWebApiDependencyResolver(container);

            // 5. register global filters //                 ,         
            //RegisterGlobalFilters(GlobalFilters.Filters, container);
        }

        //public static void RegisterGlobalFilters(GlobalFilterCollection filters, Container container)
        //{
        //}
    }

전체 웹 api 의 controller 는 다음 과 같 습 니 다.
    public class tstController : ApiController
    {
        private Iaaa _srv;
        public Ibbb s2 { get; set;} //  s2,     

        public tstController(Iaaa srv)
        {
            _srv = srv;
        }
        //        
        public string get(string id)
        {
            return _srv.hello(id);
        }
       //      
        public string get()
        {
            return s2.curtime;
        }
    }

    이름 을 마음대로 지 었 으 니 양해 해 주 십시오.    방문 / api / tst /, current time is: 2013 - 12 - 15T 23: 06: 00, 우 리 는 구조 기 에서 Ibbb 를 초기 화 하지 않 았 으 나, 이미 aaa 대상 에서 값 을 찾 아 테스트 에 통과 하 였 습 니 다.
4, 예시 코드
git clone https://github.com/walkerwzy/simpleinjectorSample.git

좋은 웹페이지 즐겨찾기