.NET中的依赖注入与示例?

有人可以用一个基本的.NET示例解释依赖注入,并提供一些链接到.NET资源以扩展主题

这不是What is dependency injection?的重复,因为我问特定的.NET示例和资源。

这里有一个常见的例子。您需要登录您的应用程序。但是,在设计时,您不确定客户端是否希望登录数据库文件或事件日志。

所以,你想使用DI来推迟这个选择,可以由客户端配置。

这是一些伪码(大致基于Unity):

您创建一个日志接口:

public interface ILog
{
  void Log(string text);
}

然后在你的类中使用这个接口

public class SomeClass
{
  [Dependency]
  public ILog Log {get;set;}
}

在运行时注入这些依赖

public class SomeClassFactory
{
  public SomeClass Create()
  {
    var result = new SomeClass();
    DependencyInjector.Inject(result);
    return result;
  }
}

并在app.config中配置实例:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name ="unity"
             type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity>
    <typeAliases>
      <typeAlias alias="singleton"
                 type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager,Microsoft.Practices.Unity" />
    </typeAliases>
    <containers>
      <container>
        <types>
          <type type="MyAssembly.ILog,MyAssembly"
                mapTo="MyImplementations.sqlLog,MyImplementations">
            <lifetime type="singleton"/>
          </type>
        </types>
      </container>
    </containers>
  </unity>
</configuration>

现在,如果要更改记录器的类型,只需进入配置并指定另一种类型。

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...