本文介绍了如何在c#中创建自定义IoC容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建自己的自定义IoC容器,并附上每一步的说明。任何人都可以帮帮我吗?
I want to create my own custom IoC container with the explanation for every step.Can anyone please help me out?
推荐答案
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
);
这篇关于如何在c#中创建自定义IoC容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!