1.7 依赖注入:使用 Autofac 增强容器能力.pdf
拦截器
namespace DependencyInjectionAutofacDemo.Services
{
public class MyInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
Console.WriteLine($"Intercept before,Method:{invocation.Method.Name}");
// 方法执行
invocation.Proceed();
Console.WriteLine($"Intercept after,Method:{invocation.Method.Name}");
}
}
}
效果:
子容器
// 注册
builder.RegisterType<MyNameService>().InstancePerMatchingLifetimeScope("myscope");、
// 使用,在 myscope 的子容器范围内获取的都是同一对象
using (var myscope = AutofacContainer.BeginLifetimeScope("myscope"))
{
var service0 = myscope.Resolve<MyNameService>();
using (var scope = myscope.BeginLifetimeScope())
{
var service1 = scope.Resolve<MyNameService>();
var service2 = scope.Resolve<MyNameService>();
Console.WriteLine($"service1=service2:{service1 == service2}");
Console.WriteLine($"service1=service0:{service1 == service0}");
}
}
简单来说如果我们希望一个对象不在跟容器中创建,而它创建后在一定范围内又是单例模式时,就要用到子容器。