Closed SeriousM closed 6 years ago
By default the lifestyle is transient, there isn't anything out of the box to assign lifestyles. What's the use case you are trying to accomplish?
I work with a legacy system that contains millions of static stateful classes. I will replace the statics with instances which are singleton and wanted to avoid telling that every singe element is singleton. Instead, everything is singleton and only a few are different.
Gotcha, ok so you have a couple options.
1) Use the Export(IEnumerable<Type>)
method that allows for bulk registration of types and allows assigning a lifestyle
2) Implement an IActivationStrategyInspector
and set the lifestyle there (you have to cast the IActivationStrategy
to IConfigurableActivationStrategy
to set lifestyle but that shouldn't be a problem)
That worked pretty well, thank you!
Here is the code for others that have the same task:
public class MarkAllAsSingletonLifestyle : IActivationStrategyInspector
{
private readonly Func<Type, bool> picker;
public MarkAllAsSingletonLifestyle(Func<Type, bool> picker)
{
this.picker = picker;
}
public void Inspect<T>(T strategy) where T : class, IActivationStrategy
{
if (!picker.Invoke(strategy.ActivationType)
|| !(strategy is IConfigurableActivationStrategy configurableStrategy))
{
return;
}
if (configurableStrategy.Lifestyle == null)
{
configurableStrategy.Lifestyle = new SingletonLifestyle();
}
}
}
That's pretty much what I was thinking.
How can I set a default lifestyle? I found
IActivationStrategy.Lifestyle
and tried to get an instance to manipulate it but there are soooo many services so that I wasn't able to find one.Is there a way to set a default value?