惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

AI
AI
GbyAI
GbyAI
Blog — PlanetScale
Blog — PlanetScale
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
L
LangChain Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
U
Unit 42
aimingoo的专栏
aimingoo的专栏
N
Netflix TechBlog - Medium
H
Hackread – Cybersecurity News, Data Breaches, AI and More
A
About on SuperTechFans
B
Blog
I
InfoQ
T
The Exploit Database - CXSecurity.com
H
Heimdal Security Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
L
LINUX DO - 最新话题
Google Online Security Blog
Google Online Security Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Help Net Security
Help Net Security
Stack Overflow Blog
Stack Overflow Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
Threat Research - Cisco Blogs
量子位
P
Privacy & Cybersecurity Law Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
SecWiki News
SecWiki News
S
Security @ Cisco Blogs
Cisco Talos Blog
Cisco Talos Blog
博客园_首页
The Last Watchdog
The Last Watchdog
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
小众软件
小众软件
有赞技术团队
有赞技术团队
NISL@THU
NISL@THU
WordPress大学
WordPress大学
K
Kaspersky official blog
D
DataBreaches.Net
Hugging Face - Blog
Hugging Face - Blog
Vercel News
Vercel News
雷峰网
雷峰网
Webroot Blog
Webroot Blog
B
Blog RSS Feed
W
WeLiveSecurity
Scott Helme
Scott Helme
A
Arctic Wolf
阮一峰的网络日志
阮一峰的网络日志
G
Google Developers Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO

博客园 - 无名365

.NET 2.0 JSON Parser Provisioning 是什么意思? SOA与云计算 Good understand on WCF Data Contract & Serialization WCF DataContract EmitDefaultValue a xml configuration for unity and interception Programmatically Compress and Decompress Files using c# CodeRun Studio - A free cloud develop and debug service for .Net Cloud IDE 10个最“优秀”的代码注释 Compress and Decompress JQuery Mobile 1.0 Released, Gets Mixed Reaction Interceptor in Unity and Policy Injection in Unity Configuring Unity Container with Policy Injection Configuration Unity Configuration Node IoC and Unity - Configuration Objects and the Art of Data Modeling AppFabric Cache - Cache Cluster EF - How to delete an object without retrieving it LINQ to SQL Extension: Batch Deletion with Lambda Expression
Unity Configuration from Separate Configuration File
无名365 · 2011-11-22 · via 博客园 - 无名365

2011-11-22 09:42  无名365  阅读(757)  评论()    收藏  举报

I mentioned on Twitter the other day that if you have to configure Unity via a configuration file, you probably want to do it in a separate configuration file. Personally I think this is a best practice when using any of the Application Blocks in Enterprise Library, too, but I realize the experience can be a bit of a burden.

A few people asked me for an example of configuring Unity in a separate configuration file which is the motivation for this post. The Unity Documentation is pretty good on this topic. In fact, I pretty much just copy and pasted the code for reading from a separate file in this post, but this post might be a bit easier to find the information.

Reading Unity Configuration from Separate Configuration File

In this example, I am using a simple Console Application. The configuration information is in a separate configuration file, called unity.config, which has one container, called container, that maps a UserRepository to IUserRepository. The UserRepository constructor requires a connection string so I specified the connection string in the constructor parameters in the type configuration.

Program.cs

The GetContainer Method is pretty much boiler-plate code responsible for reading the unity.config file and populating a new container with the configuration information. You could make it more generic by passing in parameters for the name of the file, name of the container, etc. This is basically straight out of the documentation:

private static void Main(string[] args)

{

    IUnityContainer container = GetContainer();

    var repository = container.Resolve<IUserRepository>();

}

private static IUnityContainer GetContainer()

{

    var map = new ExeConfigurationFileMap();

    map.ExeConfigFilename = "unity.config";

    var config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);

    var section = (UnityConfigurationSection) config.GetSection("unity");

    var container = new UnityContainer();

    section.Containers["container"].Configure(container);

    return container;

}

Unity.config

The configuration file sets up some aliases, specifies the mapping between IUserRepository and UserRepository, provides an example of using a singleton lifetime manager, and contains type configuration that specifies how to construct the UserRepository:

<?xml version="1.0"?>

<configuration>

  <configSections>

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

  </configSections>

  <unity>

    <typeAliases>

      <typeAlias alias="string" type="System.String, mscorlib" />

      <typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />

      <typeAlias alias="IUserRepository" type="ConsoleApplication3.IUserRepository, ConsoleApplication3" />

      <typeAlias alias="UserRepository" type="ConsoleApplication3.UserRepository, ConsoleApplication3" />

    </typeAliases>

    <containers>

      <container name="container">

        <types>

          <type type="IUserRepository" mapTo="UserRepository" >

            <lifetime type="singleton" />

            <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration">

              <constructor>

                <param name="connectionString" parameterType="string">

                  <value value="[YourConnectionString]"/>

                </param>

              </constructor>

            </typeConfig>

          </type>

        </types>

      </container>

    </containers>

  </unity>

</configuration>

IUserRepository and UserRepository

And last, a barebones illustration of the interface and concrete implementations of the types just to illustrate the use of the configuration file:

public interface IUserRepository {}

public class UserRepository : IUserRepository

{

    public string ConnectionString { get; private set; }

    public UserRepository(string connectionString) {

        ConnectionString = connectionString;

    }

}

Conclusion

Hopefully this helps you configure Unity in a separate configuration file. I think this is always a good idea as it keep your IoC / Dependency Injection configuration information separate from application settings in your app.config or web.config.

From http://www.pnpguidance.net/post/UnityConfigurationSeparateConfigurationFile.aspx