Default the LifetimeManager to the singleton manager (ContainerControlledLifetimeManager)?

自古美人都是妖i 提交于 2019-12-10 11:29:19

问题


I'm using a Unity IoC container to do Dependency Injection. I designed my system around the idea that, at least for a single resolution, all types in the hierarchy would behave as singletons, that is, same type resolutions within that hierarchy would lead to the same instances.

However, I (a) would like to scan my assemblies to find types and (b) don't want to explicitly tell unity that every type is to be resolved as a singleton when registering types in the configuration file.

So, is there a way to tell unity to treat all registered mappings as singleton?


回答1:


In case anyone is still looking for this... The following extension will change the default, while still allowing you to override with some other manager:

/// <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);
            }
        }
    }
}



回答2:


You could add a Unity extension at the 'Lifetime' stage of the resolution pipeline and in it always use a ContainerControlledLifetimeManager instance.

Edit: In fact this post has the exact example:

https://unity.codeplex.com/discussions/352179



来源:https://stackoverflow.com/questions/29828410/default-the-lifetimemanager-to-the-singleton-manager-containercontrolledlifetim

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!