Autofac注入方式
Autofac三种注入方式
l 构造函数注入
l 属性注入
l 方法注入
实践
项目结构
在上节Autofac的快速入门的项目上改造。
添加ITestServiceB 和 TestServiceB
public interface ITestServiceB { void Show(); } public class TestServiceB : ITestServiceB { private ITestServiceA _testServiceA;
public TestServiceB() { Console.WriteLine($"{this.GetType().Name} 被构造了..."); } public void SetService(ITestServiceA testServiceA) { _testServiceA = testServiceA; }
public void Show() { _testServiceA.Show(); Console.WriteLine($"This is a {this.GetType().Name} Instance..."); } } |
添加ITestServiceC 和 TestServiceC
public interface ITestServiceC { void Show(); } public class TestServiceC : ITestServiceC { private ITestServiceA _testServiceA; public TestServiceC(ITestServiceA iTestServiceA) { _testServiceA = iTestServiceA; Console.WriteLine($"{this.GetType().Name} 被构造了..."); }
public void Show() { _testServiceA.Show(); Console.WriteLine($"This is a {this.GetType().Name} Instance..."); } } |
添加ITestServiceD 和 TestServiceD
public interface ITestServiceB { void Show(); } public class TestServiceD : ITestServiceD { public ITestServiceA TestServiceA { get; set; } public ITestServiceB TestServiceB { get; set; } public ITestServiceC TestServiceC { get; set; }
public TestServiceD() { Console.WriteLine($"{this.GetType().Name} 被构造了..."); }
public void Show() { TestServiceA.Show(); //TestServiceB.Show(); TestServiceC.Show(); Console.WriteLine($"This is a {this.GetType().Name} Instance..."); } } |
构造函数注入
构造器注入是默认行为,不需要设置。
var builder = new ContainerBuilder(); builder.RegisterType<TestServiceA>().As<ITestServiceA>(); builder.RegisterType<TestServiceC>().As<ITestServiceC>(); var container = builder.Build(); // 获取服务实例 var testService = container.Resolve<ITestServiceC>(); testService.Show(); |
运行:
属性注入
提供属性的服务,注册时候必须使用PropertiesAutowired方法。
var builder = new ContainerBuilder(); builder.RegisterType<TestServiceA>().As<ITestServiceA>(); builder.RegisterType<TestServiceD>().As<ITestServiceD>().PropertiesAutowired(); var container = builder.Build(); // 获取服务实例 var testService = container.Resolve<ITestServiceD>(); testService.Show(); |
方法注入
提供方法注入,需要在注册服务的时候,使用OnActivated方法。
var builder = new ContainerBuilder(); builder.RegisterType<TestServiceA>().As<ITestServiceA>(); builder.RegisterType<TestServiceB>().OnActivated(e => e.Instance.SetService(e.Context.Resolve<ITestServiceA>()) ).As<ITestServiceB>(); var container = builder.Build();
// 获取服务实例 var testService = container.Resolve<ITestServiceB>(); testService.Show(); |
运行:
总结
通过构造函数传入接口进行获取实例,该方法可以极大减少构造函数传入的实例过多所导致的构造函数参数臃肿。