ipjohnson / Grace

Grace is a feature rich dependency injection container library
MIT License
336 stars 33 forks source link

Default Lifestyle for Scope/Container #164

Closed SeriousM closed 6 years ago

SeriousM commented 6 years ago

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?

ipjohnson commented 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?

SeriousM commented 6 years ago

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.

ipjohnson commented 6 years ago

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)

SeriousM commented 6 years ago

That worked pretty well, thank you!

SeriousM commented 6 years ago

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();
    }
  }
}
ipjohnson commented 6 years ago

That's pretty much what I was thinking.