创建容器后如何在autofac中注册类型

编程入门 行业动态 更新时间:2024-10-26 01:31:29
本文介绍了创建容器后如何在autofac中注册类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个基础结构单例,我想从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中注册类型

本文发布于:2023-11-04 12:26:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557936.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:容器   类型   如何在   autofac

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!