Skip to content

Dependency Injection

DUONG Phu-Hiep edited this page Aug 27, 2024 · 3 revisions

What is service locator - the anti-pattern?

class Toto {
  ctor(IServiceProvider s)
}

=> depend directly on the ServiceProvider and use it to resolve the required Dependency

Source: https://medium.com/volosoft/asp-net-core-dependency-injection-best-practices-tips-tricks-c6e9c67f9d96

MultiTenant DI

https://github.com/duongphuhiep/AsyncInjectionTutorial/blob/master/SampleApi.AsyncInjection/README.md

Compare DI frameworks Aug 2024

My choice: DryIoc

  • Fairly popular
  • Active development: lot of commits (total commit, and recent commits)
  • All documentation's codes is runnable tests codes => feels very reliable.

image image image image image image

Ninject

image

SimpleInjector

image

DryIoc

image

LightInject

image

StashBox

image

Support for Property injection

Autofac:

builder.Register(c => new A { B = c.Resolve<B>() });

Ninject: (15 ans, no new commit since 2 years, 80 issues)

class Samurai 
{    
    [Inject]
    public IWeapon Weapon { get; set; }
}

Simpleinjector (15 ans / 2259 commits / 27 issues)

container.RegisterInitializer<HandlerBase>(handlerToInitialize => {
    handlerToInitialize.ExecuteAsynchronously = true;
});

Or

class ImportPropertySelectionBehavior : IPropertySelectionBehavior
{
    public bool SelectProperty(Type implementationType, PropertyInfo prop) =>
        prop.GetCustomAttributes(typeof(ImportAttribute)).Any();
}
container.Options.PropertySelectionBehavior = new ImportPropertySelectionBehavior();

LightInject (13ans / 990 commits / 80 issues)

container.RegisterPropertyDependency<IBar>((factory, propertyInfo) => new Bar());

Dryloc (11 ans/ 4754 commits) doc is unsearchable (cs2md)! Very active development

var ws = c.Resolve<IWidgetService>();
c.InjectPropertiesAndFields(ws);

Or

c.Register<IWidgetService, WidgetService>(Reuse.Singleton, 
     made: PropertiesAndFields.Of.Name("WidgetRepository"));

or strongly typed:

c.Register<IWidgetService, WidgetService>(
    Made.Of(() => new WidgetService { WidgetRepository = Arg.Of<IWidgetRepository>() }),
    Reuse.Singleton);

Stashbox good docs, Very active development

options.WithAutoMemberInjection(
    Rules.AutoMemberInjectionRules.PropertiesWithPublicSetter)