问题
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"]));
}
回答1:
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.
回答2:
I think you can register all services by manual scanning. And then register them to Service collection. Here is my example code (.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));
}
}
}
回答3:
I also wanted to give the built-in a try, got annoyed with the lack of auto-register and built an open-source project for that, take a look:
https://github.com/SharpTools/SharpDiAutoRegister
Just add the nuget package SharpDiAutoRegister
and add your conventions in the ConfigureServices method:
services.ForInterfacesMatching("^I[a-zA-z]+Repository$")
.OfAssemblies(Assembly.GetExecutingAssembly())
.AddSingletons();
services.ForInterfacesMatching("^IRepository")
.OfAssemblies(Assembly.GetExecutingAssembly())
.AddTransients();
//and so on...
回答4:
ASP.NET Core is designed from the ground up to support and leverage dependency injection.
ASP.NET Core applications can leverage built-in framework services by having them injected into methods in the Startup class, and application services can be configured for injection as well.
The default services container provided by ASP.NET Core provides a minimal feature set and is
not intended to replace other containers.
Source: https://docs.asp.net/en/latest/fundamentals/dependency-injection.html
The default ASP.NET container is
simple and does not offer the robust configuration and performance options that are available with other containers.
Fortunately, you can swap out the default container with one of the community-created full featured ones that is already available as a NuGet package.
Autofac (http://autofac.org/ ) is one that is already available for ASP.NET Core, and you can add it to your project by referencing both the
Autofac and
Autofac.Extensions.DependencyInjection packages.
Source: https://blogs.msdn.microsoft.com/webdev/2016/03/28/dependency-injection-in-asp-net-core/
来源:https://stackoverflow.com/questions/36662122/dependency-injection-in-asp-net-core