|
Hi Randy!
I tried you approach and modified it to this extension:
public class DefaultLifetimeManagerExtension<TLifetimeManager> : UnityContainerExtension where TLifetimeManager : ILifetimePolicy, new()
{
protected override void Initialize()
{
Context.Strategies.Add(new DefaultLifetimeManagerStrategy(), UnityBuildStage.Creation);
}
#region Nested type: DefaultLifetimeManagerStrategy
private class DefaultLifetimeManagerStrategy : BuilderStrategy
{
public override void PreBuildUp(IBuilderContext context)
{
Debug.WriteLine(string.Format("Setting ILifetimePolicy to {0} for build key {1}.",
typeof (TLifetimeManager).Name, context.BuildKey), "DefaultLifetimeManagerExtension");
// This overrides the current LifetimeManager.
// We should only apply a new policy if we don't have a registered LifetimeManager.
// No way to know here whether the current LifetimeManager is the custom registered one,
// or the TransientLifetimeManager added by Unity by default.
context.PersistentPolicies.Set<ILifetimePolicy>(new TLifetimeManager(), context.BuildKey);
}
}
#endregion
}
As you can see in the comments, this does not respect custom LifetimeManager registrations. With this piece of code, all objects are created using the default LifetimeManager...
The problem is that the LifetimeStrategy already injects the default policy before the code above is called:
private static ILifetimePolicy GetLifetimePolicy(IBuilderContext context)
{
ILifetimePolicy policy = context.Policies.GetNoDefault<ILifetimePolicy>(context.BuildKey, false);
if(policy == null && context.BuildKey.Type.IsGenericType)
{
policy = GetLifetimePolicyForGenericType(context);
}
if(policy == null)
{
policy = new TransientLifetimeManager();
context.PersistentPolicies.Set<ILifetimePolicy>(policy, context.BuildKey);
}
return policy;
}
Due to this behavior, I suspect it is impossible to know whether the assigned ILifetimePolicy has been assigned via a custom type registration, or set as the default TransientLifetimeManager by the LifetimeStrategy.
|