在AutoFac中,可以通过上下文解析来获取依赖注入的实例。下面是一个基本的示例代码:
using Autofac;
public class MyDependency
{
public void DoSomething()
{
Console.WriteLine("MyDependency is doing something...");
}
}
public class MyClass
{
private readonly MyDependency _dependency;
public MyClass(MyDependency dependency)
{
_dependency = dependency;
}
public void Execute()
{
_dependency.DoSomething();
}
}
public static class Program
{
public static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType();
builder.RegisterType();
using (var container = builder.Build())
{
var myClass = container.Resolve();
myClass.Execute();
}
}
}
在上面的示例中,MyClass
依赖于MyDependency
,并通过构造函数注入。当调用container.Resolve
时,AutoFac会自动解析MyDependency
并传递给MyClass
的构造函数。
这样,我们就可以通过上下文解析来获取依赖注入的实例。