gpt4 book ai didi

c# - 将 LifetimeManager 默认为单例管理器 (ContainerControlledLifetimeManager)?

转载 作者:太空宇宙 更新时间:2023-11-03 10:31:50 25 4
gpt4 key购买 nike

我正在使用 Unity IoC 容器进行依赖注入(inject)。我围绕这样的想法设计我的系统,即至少对于单个解析,层次结构中的所有类型都将表现为单例,也就是说,该层次结构中的相同类型解析将导致相同的实例。

但是,我 (a) 想扫描我的程序集以查找类型,并且 (b) 不想明确告诉 unity 在配置文件中注册类型时每个类型都将解析为单例。

那么,有没有办法告诉 unity 将所有已注册的映射视为单例?

最佳答案

万一有人还在寻找这个...下面的扩展将更改默认值,同时仍然允许您用其他一些管理器覆盖:

/// <summary>
/// This extension allows the changing of the default lifetime manager in unity.
/// </summary>
public class DefaultLifetimeManagerExtension<T> : UnityContainerExtension where T : LifetimeManager
{
/// <summary>
/// Handle the registering event
/// </summary>
protected override void Initialize()
{
Context.Registering += this.OnRegister;
}

/// <summary>
/// Remove the registering event
/// </summary>
public override void Remove()
{
Context.Registering -= this.OnRegister;
}

/// <summary>
/// Handle the registration event by checking for null registration
/// </summary>
private void OnRegister(object sender, RegisterEventArgs e)
{
if (e.LifetimeManager == null)
{
var lifetimeManager = (LifetimeManager)Activator.CreateInstance(typeof (T));

// Set this internal property using reflection
lifetimeManager
.GetType()
.GetProperty("InUse", BindingFlags.NonPublic | BindingFlags.Instance)
.SetValue(lifetimeManager, true);

Context.Policies.Set<ILifetimePolicy>(lifetimeManager, new NamedTypeBuildKey(e.TypeTo, e.Name));

if (lifetimeManager is IDisposable)
{
Context.Lifetime.Add(lifetimeManager);
}
}
}
}

关于c# - 将 LifetimeManager 默认为单例管理器 (ContainerControlledLifetimeManager)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29828410/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com