Dependency Injection in ASP.NET Kernel

In Autofac, you can register your dependencies with RegisterAssemblyTypes so you can do something like this, is there a way to do something like this in building in DIfor.net Core

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

This is what I'm 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 try to register with Regisyer, but I cannot figure out how to register Startup.cs repositories

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"]));
}
+4
source share
4 answers

It is not possible to do this using the ASP.NET Core Dependency Injection / IoC application, but it is “by design”.

ASP.NET IoC Container/DI DI IoC, ASP.NET.

(, , ), , .

/ IoC (AutoFac, StructureMap ..). IServiceCollection, , .

+4

, . . (.Net core 2.0)

public static void ResolveAllTypes(this IServiceCollection services, string solutionPrefix, params string[] projectSuffixes)
        {
            //solutionPrefix is my Solution name, to separate with another assemblies of Microsoft,...
            //projectSuffixes is my project what i want to scan and register
            //Note: To use this code u must reference your project to "projectSuffixes" projects.

            var allAssemblies = new List<Assembly>();
            var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

            foreach (var dll in Directory.GetFiles(path, "*.dll"))
                allAssemblies.Add(Assembly.LoadFile(dll));


            var types = new List<Type>();
            foreach (var assembly in allAssemblies)
            {
                if (assembly.FullName.StartsWith(solutionPrefix))
                {
                    foreach (var assemblyDefinedType in assembly.DefinedTypes)
                    {
                        if (projectSuffixes.Any(x => assemblyDefinedType.Name.EndsWith(x)))
                        {
                            types.Add(assemblyDefinedType.AsType());

                        }
                    }
                }
            }

            var implementTypes = types.Where(x => x.IsClass).ToList();
            foreach (var implementType in implementTypes)
            {
                //I default "AService" always implement "IAService", You can custom it
                var interfaceType = implementType.GetInterface("I" + implementType.Name);

                if (interfaceType != null)
                {
                    services.Add(new ServiceDescriptor(interfaceType, implementType,
                        ServiceLifetime.Scoped));
                }

            }

        }
+2

ASP.NET Core , .

ASP.NET Core , Startup, .

, ASP.NET Core,

.

: https://docs.asp.net/en/latest/fundamentals/dependency-injection.html


ASP.NET

.

, , NuGet.

Autofac (http://autofac.org/) - , ASP.NET Core, ,

Autofac

Autofac.Extensions.DependencyInjection.

: https://blogs.msdn.microsoft.com/webdev/2016/03/28/dependency-injection-in-asp-net-core/

0

, . :

https://github.com/SharpTools/SharpDiAutoRegister

nuget SharpDiAutoRegister ConfigureServices:

services.ForInterfacesMatching("^I[a-zA-z]+Repository$")
        .OfAssemblies(Assembly.GetExecutingAssembly())
        .AddSingletons();

services.ForInterfacesMatching("^IRepository")
        .OfAssemblies(Assembly.GetExecutingAssembly())
        .AddTransients();

//and so on...
0

All Articles