依赖注入在.NET中使用的例子吗?例子、NET

2023-09-02 10:22:04 作者:我姓刘却留不住你的心

有人能解释依赖注入 与 Basic .NET示例并提供一些链接到.NET资源,关于这个问题的延伸?

Can someone explain dependency injection with a basic .NET example and provide a few links to .NET resources to extend on the subject?

这是不是http://stackoverflow.com/questions/130794/what-is-dependency-injection因为我问具体.NET的例子和资源。

This is not a duplicate of http://stackoverflow.com/questions/130794/what-is-dependency-injection because I am asking about specific .NET examples and resources.

推荐答案

下面是一个常见的​​例子。您需要登录您的应用程序。但是,在设计时,你不知道,如果客户想登录到数据库,文件或事件日志。

Here's a common example. You need to log in your application. But, at design time, you're not sure if the client wants to log to a database, files, or the event log.

所以,你想用DI给选择推迟到一种可通过客户端进行配置。

So, you want to use DI to defer that choice to one that can be configured by the client.

这是一些伪code(约基于统一):

This is some pseudocode (roughly based on Unity):

您创建一个日志接口:

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

然后使用这个接口在类中

then use this interface in your classes

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

注入这些依赖在运行时

inject those dependencies at runtime

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

和实例配置中的app.config:

and the instance is configured in 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>

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

Now if you want to change the type of logger, you just go into the configuration and specify another type.