配置文件中加上:
<configSections>
<section name="autofac" type="Autofac.Configuration.SectionHandler, Autofac.Configuration"/>
</configSections>
<autofac defaultAssembly="AutoFacTest">
<components>
<component name="write2" type="WriteImpl2.Write, WriteImpl2" service="WriteTest.IWrite, WriteTest"/>
<component name="write1" type="WriteImpl.Write, WriteImpl" service="WriteTest.IWrite, WriteTest" />
<component name="DateUtils" type="Commons.DateUtils, Commons" service="Commons.DateUtils, Commons" />
</components>
</autofac>
其中 根结点 autofac defaultAssembly表示运行程序集的名字
子节点 component : name 表示在获取的时候的唯一名字, type- 类的全名称,程序集名字 service-继承的接口(如果没继承跟type一样即可)
代码实现:
帮助类 AutofacUtils:
public class AutoFacUtils
{
private static ContainerBuilder builder = new ContainerBuilder();
private static IContainer container;
static AutoFacUtils()
{
//注册配置
builder.RegisterModule(new ConfigurationSettingsReader("autofac"));
//IContainer只能实例化一次
container = builder.Build();
}
/// <summary>
/// 获取一个实例
/// </summary>
/// <typeparam name="T">返回类型</typeparam>
/// <param name="key">component的名字</param>
/// <param name="ps">构造函数的参数</param>
/// <returns></returns>
public static T GetInstance<T>(string key, params Parameter[] ps)
{
return container.ResolveNamed<T>(key, ps);
}
}
调用:
class Program
{
static void Main(string[] args)
{
//构造函数的参数 //参数名字, 值
Parameter p = new NamedParameter("name", "hhx123");
//获取iwrite的实例
IWrite write = AutoFacUtils.GetInstance<IWrite>("write2", p);
//调用方法
write.WriteAdd(1,2);
Console.Read();
}
}