.NET 中的依赖注入示例? [英] Dependency Injection in .NET with examples?
问题描述
有人可以解释依赖注入 一个基本的 .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;}
}
在运行时注入这些依赖
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.
这篇关于.NET 中的依赖注入示例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!