微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.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>

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

原文地址:https://www.jb51.cc/javaschema/282427.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐