Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependency Injection in ASP.NET Core

In Autofac you can register your dependencies with RegisterAssemblyTypes so you will be able todo something like this, is there a way to do the somthing similar in the build in DI for .net Core

builder.RegisterAssemblyTypes(Assembly.Load("SomeProject.Data"))
    .Where(t => t.Name.EndsWith("Repository"))
    .AsImplementedInterfaces()
    .InstancePerLifetimeScope();

This is what i am trying to register

LeadService.cs

public class LeadService : ILeadService
{
    private readonly ILeadTransDetailRepository _leadTransDetailRepository;

    public LeadService(ILeadTransDetailRepository leadTransDetailRepository)
    {
        _leadTransDetailRepository = leadTransDetailRepository;
    }
}

LeadTransDetailRepository.cs

public class LeadTransDetailRepository : RepositoryBase<LeadTransDetail>, 
    ILeadTransDetailRepository
{
    public LeadTransDetailRepository(IDatabaseFactory databaseFactory) 
        : base(databaseFactory) { }
}

public interface ILeadTransDetailRepository : IRepository<LeadTransDetail> { }

This is how i am trying to Regisyer then, but i cant figure out how to register the repositories Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    services.AddTransient<ILeadService, LeadService>();

    //not sure how to register the repositories
    services.Add(new ServiceDescriptor(typeof(ILeadTransDetailRepository),
        typeof(IRepository<>), ServiceLifetime.Transient));

    services.Add(new ServiceDescriptor(typeof(IDatabaseFactory),
        typeof(DatabaseFactory), ServiceLifetime.Transient));
    services.AddTransient<DbContext>(_ => new DataContext(
        this.Configuration["Data:DefaultConnection:ConnectionString"]));
}
like image 761
R4nc1d Avatar asked Apr 16 '16 08:04

R4nc1d


1 Answers

There is no out of the box way to do it with ASP.NET Core Dependency Injection/IoC container, but it's "by design".

ASP.NET IoC Container/DI is meant to be an easy way to add DI functionality and works as a base for other IoC Container frameworks to be built into ASP.NET Core apps.

That being said it supports simple scenarios (registrations, trying to use the first constructor with most parameters that fulfills the dependencies and scoped dependencies), but it lacks advanced scenarios like auto-registration or decorator support.

For this features you'll have to use 3rd party libraries and/or 3rd party IoC container (AutoFac, StructureMap etc.). They can still be plugged into the IServiceCollection your your previous registrations will still work, but you get additional features on top of it.

like image 142
Tseng Avatar answered Sep 28 '22 14:09

Tseng