帮助我在没有配置文件的情况下统一实现DI [英] Help me to implement DI with unity without config file
问题描述
我熟悉如何与配置文件一起实现Di.所以我在这里发布我的代码,其中已经使用了配置文件.所以任何人只要看看我的代码即可实现相同的功能,而无需配置文件,例如寄存器类型和解析 基于条件的实例.
i am familiar with how to implement Di with unity with config file. so here i am posting my code where config file has been used. so anyone just have a look at my code and implement the same functionality without config file like register type and resolve instance based on condition.
让我们定义一个接口
public interface ILogger
{
void Write(string message);
}
我们定义了以下三个类.
We have define three classes as follows.
public class FileLogger : ILogger
{
public void Write(string message)
{
//Do somthing
}
}
public class SQLLogger : ILogger
{
public void Write(string message)
{
//Do somthing
}
}
public class WindowsEventLogger : ILogger
{
public void Write(string message)
{
//Do somthing
}
}
需要使用接口在配置文件(即app.config)中注册和映射这些类.
Need to register and map these classes with interface in configuration file (i.e. app.config).
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias type="UnityTest.ILogger, UnityTest" alias="ILogger" />
<namespace name="UnityTest"/>
<container>
<register mapTo="UnityTest.FileLogger, UnityTest" name="MyFileLogger" type="ILogger"/>
<register mapTo="UnityTest.SQLLogger, UnityTest" name="MySQLLogger" type="ILogger"/>
<register mapTo="UnityTest.WindowsEventLogger, UnityTest" name="MyWindowsEventLogger" type="ILogger"/>
</container>
</unity>
注意:名称属性在注册代码中很重要.
Note: name attribute is important in register tag.
最后,我们必须将此映射用于我们的代码中.因此,我们必须知道,哪个国家/地区适合特定国家/地区.
Finally we have to use this map into our code. So, we have to know that for which one is preferable for specific country.
可以使用字典对象来保持此映射,如下所示.
A dictionary object can be use to keep this mapping as follows.
IDictionary<string, string> loggers = new Dictionary<string, string>();
loggers.Add("USA", "MyFileLogger");
loggers.Add("GBR", "MySQLLogger");
loggers.Add("IN", "MyWindowsEventLogger");
您可以从数据库,xml或其他来源填充它,现在是时候调用Write方法了.
You can populate it from database, xml or another source, and now it's time to call the Write method.
IUnityContainer container = new UnityContainer();
container.LoadConfiguration();
ILogger logger = container.Resolve<ILogger>(loggers[objUser.countryCode]);
logger.Write("Hello World");
推荐答案
如果您正在谈论的是依赖注入而不更改配置文件.您可能想使用其他技术.
If you are talking about Dependency Injection without changing config file. You might want to use another technology.
http://fluentnhibernate.codeplex.com/
http://fluentnhibernate.codeplex.com/
chanmm
这篇关于帮助我在没有配置文件的情况下统一实现DI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!