Joh*_*dol 28 .net dependency-injection
有人可以用基本的.NET示例来解释依赖注入 , 并提供一些指向.NET资源的链接来扩展这个主题吗?
小智 33
这是一个常见的例子.您需要登录您的应用程序.但是,在设计时,您不确定客户端是否要记录到数据库,文件或事件日志.
因此,您希望使用DI将该选择推迟到可由客户端配置的选项.
这是一些伪代码(大致基于Unity):
您创建一个日志记录界面:
public interface ILog
{
void Log(string text);
}
Run Code Online (Sandbox Code Playgroud)
然后在您的类中使用此接口
public class SomeClass
{
[Dependency]
public ILog Log {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
在运行时注入这些依赖项
public class SomeClassFactory
{
public SomeClass Create()
{
var result = new SomeClass();
DependencyInjector.Inject(result);
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
并在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>
Run Code Online (Sandbox Code Playgroud)
现在,如果要更改记录器的类型,只需进入配置并指定其他类型即可.
Sam*_*ron 32
Ninject必须有一个最酷的样本:(从样本拼凑)
interface IWeapon {
void Hit(string target);
}
class Sword : IWeapon {
public void Hit(string target) {
Console.WriteLine("Chopped {0} clean in half", target);
}
}
class Shuriken : IWeapon {
public void Hit(string target) {
Console.WriteLine("Shuriken tossed on {0}", target);
}
}
class Samurai {
private IWeapon _weapon;
[Inject]
public Samurai(IWeapon weapon) {
_weapon = weapon;
}
public void Attack(string target) {
_weapon.Hit(target);
}
}
class WeaponsModule: NinjectModule {
private readonly bool _useMeleeWeapons;
public WeaponsModule(bool useMeleeWeapons) {
_useMeleeWeapons = useMeleeWeapons;
}
public void Load() {
if (useMeleeWeapons)
Bind<IWeapon>().To<Sword>();
else
Bind<IWeapon>().To<Shuriken>();
}
}
class Program {
public static void Main() {
bool useMeleeWeapons = false;
IKernel kernel = new StandardKernel(new WeaponsModule(useMeleeWeapons));
Samurai warrior = kernel.Get<Samurai>();
warrior.Attack("the evildoers");
}
}
Run Code Online (Sandbox Code Playgroud)
对我来说,这非常流利,在你开始你的道场之前,你可以决定如何武装你的武士.
归档时间: |
|
查看次数: |
47483 次 |
最近记录: |