如何在c#中创建自定义IoC容器? [英] How to create a custom IoC Container in c#?
本文介绍了如何在c#中创建自定义IoC容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建自己的自定义IoC容器,并附上每一步的说明。任何人都可以帮帮我吗?
I want to create my own custom IoC container with the explanation for every step.Can anyone please help me out?
推荐答案
嗯,这很简单,事实上,这里是容器的完整源代码:
Well, it is pretty simple, as a matter of fact, here is the full source code for the container:
public class DemoContainer
{
public delegate object Creator(DemoContainer container);
private readonly Dictionary<string, object> configuration
= new Dictionary<string, object>();
private readonly Dictionary<Type, Creator> typeToCreator
= new Dictionary<Type, Creator>();
public Dictionary<string, object> Configuration
{
get { return configuration; }
}
public void Register<T>(Creator creator)
{
typeToCreator.Add(typeof(T),creator);
}
public T Create<T>()
{
return (T) typeToCreator[typeof (T)](this);
}
public T GetConfiguration<T>(string name)
{
return (T) configuration[name];
}
}
不是很难弄清楚,对吧?客户端代码非常简单:
Not really hard to figure out, right? And the client code is as simple:
DemoContainer container = new DemoContainer();
//registering dependecies
container.Register<IRepository>(delegate
{
return new NHibernateRepository();
});
container.Configuration["email.sender.port"] = 1234;
container.Register<IEmailSender>(delegate
{
return new SmtpEmailSender(container.GetConfiguration<int>("email.sender.port"));
});
container.Register<LoginController>(delegate
{
return new LoginController(
container.Create<IRepository>(),
container.Create<IEmailSender>());
});
//using the container
Console.WriteLine(
container.Create<LoginController>().EmailSender.Port
);
阅读本文 [ ^ ]获取指向多个不同IOC容器的链接。您可以查看它们并选择您最喜欢的那个。
Read this[^] to get links to several different IOC Containers. You can look them over and pick the one you like best.
阅读Sacha Barber撰写的这篇文章野蛮人IoC [ ^ ]
Have a read of this article by Sacha Barber Barbarian IoC[^]
这篇关于如何在c#中创建自定义IoC容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文