[英]How to register a type with autofac after container creation
I have an infrastructure singleton that I would like resolved out of autofac 我有一个基础结构单例,我想从autofac中解决
At container creation I register AppPaths
as a singleton 创建容器时,我将
AppPaths
注册为单例
However, for a variety of reasons (testing, a few infrastructure things) I would like to be able to swap that instance out with a new one during runtime. 但是,由于各种原因(测试,一些基础架构方面的因素),我希望能够在运行时将实例替换为新实例。 Let's say a derived type
class AppPaths2 : AppPaths
. 假设派生类型
class AppPaths2 : AppPaths
。
I can't find the API to do this. 我找不到执行此操作的API。
I can use CommentServiceLocator to get an instance of IComponentContext
but I don't see a way to resolve stuff from there. 我可以使用CommentServiceLocator来获取
IComponentContext
的实例,但是我看不到从那里解析内容的方法。
You can use Action<T>
to change the value of your current variable. 您可以使用
Action<T>
更改当前变量的值。
Foo foo = new Foo();
builder.RegisterInstance(foo);
builder.Register<Action<Foo>>(c => newFoo => foo = newFoo);
Then, you will be able to change current Foo
using : 然后,您将可以使用以下命令更改当前的
Foo
:
Action<Foo> fooUpdater = c.Resolve<Action<Foo>>()();
fooUpdater(new Foo());
You can also use a FooContainer
. 您也可以使用
FooContainer
。
class FooContainer
{
public FooContainer(Foo originalValue)
{
this.Value = originalValue;
}
public Foo Value { get; set; }
}
// ...
builder.RegisterType<FooContainer>().SingleInstance();
builder.Register(c => c.Resolve<FooContainer>().Value).As<Foo>();
// ...
c.Resolve<FooContainer>().Value = new Foo();
Another solution is to update the container : 另一个解决方案是更新容器:
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterInstance(new Foo()).AsSelf();
IContainer container = builder.Build();
using (ILifetimeScope scope = container.BeginLifetimeScope())
{
ContainerBuilder updater = new ContainerBuilder();
updater.RegisterInstance(new Foo()).AsSelf(); // new instance of Foo
updater.Update(scope.ComponentRegistry);
scope.Resolve<Foo>(); // ==> new instance of Foo
}
But doing so will only add a new registration to the component registry. 但是这样做只会将新注册添加到组件注册表中。 If you resolve
IEnumerable<Foo>
you will have all your implementations. 如果解析
IEnumerable<Foo>
,则将具有所有实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.