AutoFac
属性注册:
反射:builder.RegisterType<AutoFacManager>().PropertiesAutowired();
预先定义:builder.RegisterType<AutoFacManager>().WithProperty("person", new Worker());
构造时候:builder.Register(c => new AutoFacManager { person = c.Resolve<IPerson>() });
循环依赖,创建后:builder.Register(c => new AutoFacManager()).OnActivated(e => e.Instance.person = e.Context.Resolve<IPerson>());
生命周期:
默认生命周期,每次请求创建新对象:
builder.RegisterType<Worker>().InstancePerDependency();
单例,每次使用同一对象:builder.RegisterType<Worker>().SingleInstance();
同一个生命周期使用同一对象: builder.RegisterType<Worker>().InstancePerLifetimeScope();
上下文: builder.RegisterType<XWorker>().InstancePerMatchingLifetimeScope(MyContextHierarchy.UserSession);
var userSessionLifetime = container.BeginLifetimeScope();
userSessionLifetime.Tag = MyContextHierarchy.UserSession;
自己管理生命周期:
private Owned<IOutput> _output;
别名区分:
builder.RegisterType<Worker>().Named<IPerson>("worker");
IPerson p = container.ResolveNamed<IPerson>("worker");
枚举区分:
builder.RegisterType<Student>().Keyed<IPerson>(DeviceState.Student);
IPerson p = container.ResolveKeyed<IPerson>(DeviceState.Student);
枚举,索引获取:
IIndex<DeviceState, IPerson> IIndex = container.Resolve<IIndex<DeviceState, IPerson>>();
IPerson p = IIndex[DeviceState.Student];
构造函数选择:
参数类型: builder.RegisterType(typeof(Worker)).UsingConstructor(typeof(int));
参数: List<NamedParameter> ListNamedParameter = new List<NamedParameter>() { new NamedParameter("Id", 1), new NamedParameter("Name", "张三") };
builder.RegisterType<Worker>().WithParameters(ListNamedParameter).As<IPerson>();
自动: builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).As<IPerson>();
程序集扫描:
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).Where(t => t.Name.EndsWith("Manager"));
排除:Except<AutoFacManager)>(),Except<Worker>(ct =>ct.As<IPerson>().SingleInstance())
方法注入:
构造函数: builder.Register(c =>
{
var result = new AutoFacManager();
result.SetDependency(c.Resolve<IPerson>());
return result;
});
Activing: builder.Register<AutoFacManager>(c => new AutoFacManager()).OnActivating(e => e.Instance.SetDependency(new Worker()));
Resolve:
传递参数: AutoFacManager manager = container.Resolve<AutoFacManager>(new NamedParameter("name", "刘备"));
TypedParameter/ResolvedParameter/NamedParameter /NamedParameter 和TypedParameter
builder.Register((c, p) => new AutoFacManager(p.Named<string>("name"), c.Resolve<IPerson>()));
AutoFacManager manager = container.Resolve<AutoFacManager>(new NamedParameter("name", "刘备"));
循环依赖:
cb.Register<Worker>().OnActivated(ActivatedHandler.InjectUnsetProperties);