对比下来没感觉到 autofac 有哪些优势
///使用 autofac
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<DBLog>().As<ILog>();
builder.RegisterType<ProductService>();
var container = builder.Build();
var productService = container.Resolve<ProductService>();
///使用工厂模式
var pro = new ProductServiceNotAutofac(LogFac.GetLog());
两种方式一样可以达到目的,为什么会有autofac
public interface ILog
{
void SaveLog(string message);
}
public class DBLog : ILog
{
public DBLog()
{
Console.Write("is DBLog");
}
public void SaveLog(string message)
{
// save log here.
Console.WriteLine("DBLog here" + message);
}
}
public class TextLog : ILog
{
public TextLog()
{
Console.Write("is TextLog");
}
public void SaveLog(string message)
{
// save log here.
Console.WriteLine("TextLog here" + message);
}
}
public class ProductService
{
private ILog _log;
public ProductService(ILog log)
{
_log = log;
_log.SaveLog(" hi ");
}
}
public class ProductServiceNotAutofac
{
private ILog _log;
public ProductServiceNotAutofac(ILog log)
{
_log = log;
_log.SaveLog(" hi ");
}
}
/// <summary>
/// log工厂
/// </summary>
public static class LogFac
{
public static ILog GetLog()
{
string logk = "";
switch (logk)
{
case "dblog":
return new DBLog();
break;
case "textlog":
default:
return new TextLog();
break;
}
}
}
class Program
{
static void Main(string[] args)
{
///使用 autofac
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<DBLog>().As<ILog>();
builder.RegisterType<ProductService>();
var container = builder.Build();
var productService = container.Resolve<ProductService>();
///使用工厂
var pro = new ProductServiceNotAutofac(LogFac.GetLog());
Console.Read();
}
}
最重要的是解耦
之前看到一篇文章
我们编程就像造车 造出来的车 假如轮子需要改造一下 改成大一点的
那么我们不得不 从轮子=>底盘=>框架=>车 一层一层改造
若有了IoC(控制反转)容器那么
我们不需要依赖上一层来决定下一层的构造 轮子改动也不需要牵动底盘了
而且IoC容器还有的功能就是依赖注入 通过配置表来注入参数
这样需要改动的时候就不需要对代码再编译一次了
需要有需求经验才会更深入理解这种东西
其实我什么也不懂 :P
不对请多多指教
引用参考:
http://www.cnblogs.com/JustRu...