我有一个基础结构单例,我想从autofac中解决
I have an infrastructure singleton that I would like resolved out of autofac
在创建容器时,我将AppPaths注册为单例
At container creation I register AppPaths as a singleton
但是,由于各种原因(测试,一些基础架构方面的事情),我希望能够在运行时将实例替换为新实例.假设一个派生类型class AppPaths2 : 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.
我找不到执行此操作的API.
I can't find the API to do this.
我可以使用CommentServiceLocator来获取IComponentContext的实例,但是我看不到从那里解析内容的方法.
I can use CommentServiceLocator to get an instance of IComponentContext but I don't see a way to resolve stuff from there.
推荐答案您可以使用Action<T>更改当前变量的值.
You can use Action<T> to change the value of your current variable.
Foo foo = new Foo(); builder.RegisterInstance(foo); builder.Register<Action<Foo>>(c => newFoo => foo = newFoo);然后,您将可以使用以下命令更改当前的Foo:
Then, you will be able to change current Foo using :
Action<Foo> fooUpdater = c.Resolve<Action<Foo>>()(); fooUpdater(new Foo());您也可以使用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 }但是这样做只会将新注册添加到组件注册表中.如果您解决IEnumerable<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.
更多推荐
创建容器后如何在autofac中注册类型
发布评论