使用Autofac中的解析器可以在需要时进行运行时实例化。以下是示例代码:
using System;
using Autofac;
public interface IMyInterface
{
void DoSomething();
}
public class MyClass : IMyInterface
{
public void DoSomething()
{
Console.WriteLine("Something was done.");
}
}
public class MyConsumer
{
private readonly Func _myInterfaceFactory;
public MyConsumer(Func myInterfaceFactory)
{
_myInterfaceFactory = myInterfaceFactory;
}
public void DoSomething()
{
var myInterface = _myInterfaceFactory();
myInterface.DoSomething();
}
}
public class Program
{
public static void Main()
{
var builder = new ContainerBuilder();
builder.RegisterType().As();
builder.RegisterType();
var container = builder.Build();
var myConsumer = container.Resolve();
myConsumer.DoSomething();
}
}
上述示例代码使用了Func解析器。在MyConsumer中声明一个Func
然后通过 container.Resolve
然后,在 DoSomething 方法中调用 _myInterfaceFactory()
将会得到一个新的 IMyInterface 实例。
上一篇:Autofac中C#列表合并问题