1.7 依赖注入:使用 Autofac 增强容器能力.pdf

拦截器

  1. namespace DependencyInjectionAutofacDemo.Services
  2. {
  3. public class MyInterceptor : IInterceptor
  4. {
  5. public void Intercept(IInvocation invocation)
  6. {
  7. Console.WriteLine($"Intercept before,Method:{invocation.Method.Name}");
  8. // 方法执行
  9. invocation.Proceed();
  10. Console.WriteLine($"Intercept after,Method:{invocation.Method.Name}");
  11. }
  12. }
  13. }

效果:
image.png

子容器

  1. // 注册
  2. builder.RegisterType<MyNameService>().InstancePerMatchingLifetimeScope("myscope");、
  1. // 使用,在 myscope 的子容器范围内获取的都是同一对象
  2. using (var myscope = AutofacContainer.BeginLifetimeScope("myscope"))
  3. {
  4. var service0 = myscope.Resolve<MyNameService>();
  5. using (var scope = myscope.BeginLifetimeScope())
  6. {
  7. var service1 = scope.Resolve<MyNameService>();
  8. var service2 = scope.Resolve<MyNameService>();
  9. Console.WriteLine($"service1=service2:{service1 == service2}");
  10. Console.WriteLine($"service1=service0:{service1 == service0}");
  11. }
  12. }

image.png

简单来说如果我们希望一个对象不在跟容器中创建,而它创建后在一定范围内又是单例模式时,就要用到子容器。