我有一个具体的服务,它的行为因参数而异,我无法通过Autofac注册和解析它。正如您所看到的,通过自定义Container实现它非常容易。如何将Autofac用于此要求?
public class Container
{
Dictionary<string, MyService> _components = new Dictionary<string, MyService>();
void Register(string key,string param, string param2)
{
_components.Add(key, new MyService(param, param2, ResolveRepository()));
}
MyService ResolveMyService(string key)
{
return _components[key];
}
IRepository ResolveRepository()
{
throw new NotImplementedException();
}
}
public class MyService
{
public MyService(string param,string param2,IRepository rep ) { }
}
public interface IRepository { }
编辑:我正在尝试在Autofac中解决注册,但我们在注册过程中没有容器。
builder.RegisterType<MyService>()
.Named<MyService>("Service1")
.OnActivating(e =>
{
e.ReplaceInstance(new MyService("Service1", "param1-23", Container.Resolve<IRepository>()));
});
答案 0 :(得分:1)
您可以使用Activating
e.Context
伪事件期间访问容器
builder.RegisterType<MyService>()
.Named<MyService>("Service1")
.OnActivating(e =>
{
MyService s = new MyService("Service1",
"param1-23",
e.Context.Resolve<IRepository>())
e.ReplaceInstance();
});
但另一种选择是使用WithParameter
方法。
builder.RegisterType<MyService>()
.Named<MyService>("Service1")
.WithParameter("param1", "Service1")
.WithParameter("param2", "param1-23");