.NET中的依赖注入示例? [英] Dependency Injection in .NET with examples?

查看:119
本文介绍了.NET中的依赖注入示例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以使用 一个基本的.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?

这不是什么是依赖关系注意?,因为我正在询问具体的.NET示例和资源。

This is not a duplicate of 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.

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

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中配置: / p>

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.

这篇关于.NET中的依赖注入示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆