Unity-依赖注入之构造注入

  菜鸟有话说:对依赖注入理解不是很深,只是把学到的东西记录下来,以便日后查看。依赖注入分为构造注入、属性注入和方法注入,今天我主要介绍下构造注入。

  构造注入主要是解耦各数据层之间的调用关系,使其之间没有直接的依赖关系。

  1、首先新建IOCContainner类,只是IOC容器,ConfigureContainer()方法主要实现接口和实现类之间的匹配。

 1 static void ConfigureContainer()
 2 {
 3     /*
 4      * Add here the code configuration or the call to configure the container 
 5      * using the App configuration file
 6      */
 7     currentContainer = new UnityContainer().AddNewExtension<Interception>();
 8     //-> Adapters
 9    currentContainer.RegisterType<ITypeAdapterFactory, AutomapperTypeAdapterFactory>(new ContainerControlledLifetimeManager());
10    currentContainer.RegisterType<IUserBaseServiceImpl, UserBaseServiceImpl>();
11    currentContainer.RegisterType<IUserBaseRepository, UserBaseRepository>();
12 }

     2、在实现类里面的构造方法:

1 readonly IUserBaseRepository UserBaseRepository;
2 public UserBaseServiceImpl(IUserBaseRepository userBaseRepository)
3 {
4   this.UserBaseRepository = userBaseRepository;
5 }

    3、前台调用

1 [Dependency]
2 public IUserBaseServiceImpl UserBaseServiceImplInstance
3 {
4         get;
5         set;
6 }

 

 

posted @ 2013-07-02 10:25  情若天_RunUp  阅读(141)  评论(0编辑  收藏  举报