.net-core Dependency Injection

前端 未结 5 817
后悔当初
后悔当初 2020-12-16 04:25

I have a Generic repository which I want to register for DI, it implements an interface IRepository.

Normally I would create an instance of it like this:

<         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 05:07

    You could use a convention based registration library like Scrutor.

    Scrutor is a small open source library that provides a fluent API to register services in your Microsoft.Extensions.DependencyInjection container based on conventions (Similar to Autofac's RegisterAssemblyTypes method, StructureMap's Scan method and Ninject's Conventions package).

    This will allow you to do something like this:

    services.Scan(scan => scan
                .FromAssemblies(<>.GetTypeInfo().Assembly)
                    .AddClasses(classes => classes.Where(x => {
                        var allInterfaces = x.GetInterfaces();
                        return 
                            allInterfaces.Any(y => y.GetTypeInfo().IsGenericType && y.GetTypeInfo().GetGenericTypeDefinition() == typeof(IRepository<>)));
                    }))
                    .AsSelf()
                    .WithTransientLifetime()
            );
    

提交回复
热议问题