故如虹,知恩;故如月,知明
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
欢迎加群交流技术

c#使用unity实现依赖注入四:unity配置文件注入

7114人阅读 2019/1/23 11:03 总访问:3842391 评论:0 收藏:0 手机
分类: .NET


需要用到的配置文件


一:先向xml申明一下unity的配置文件所在的实现类

  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
  </configSections>


二:xml中配置类之间的关系

  <unity>

    <container name="UnityDll">
      <register type="DAL.IUserDAL,DAL" mapTo="DAL.UserTwoDAL,DAL"></register>
    </container>

  </unity>


三:在代码中读取xml内容

 UnityConfigurationSection section = System.Configuration.ConfigurationManager.GetSection("unity") as UnityConfigurationSection;


四:加载xml内容到容器

 //section:xml节点 
 //UnityDll:容器名称
 uc.LoadConfiguration(section, "UnityDll");


五:xml中配置生命周期


使用lifetime就可以了:例如瞬时模式

 <lifetime type="Microsoft.Practices.Unity.TransientLifetimeManager,Microsoft.Practices.Unity" />

单利模式

 <lifetime type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity" />

其实就是和后台一样的,只是使用的是类全面+程序集名称


完整一点的写法:

  <unity>

    <container name="UnityDll">
      <register type="DAL.IUserDAL,DAL" mapTo="DAL.UserTwoDAL,DAL">
        <lifetime type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity" />
      </register>
    </container>

  </unity>



欢迎加群讨论技术,群:677373950(满了,可以加,但通过不了),2群:656732739

评价