C# ASP.NET内核中的高级依赖项注入
我有以下接口、抽象类等C# ASP.NET内核中的高级依赖项注入,c#,dependency-injection,asp.net-core,C#,Dependency Injection,Asp.net Core,我有以下接口、抽象类等 public interface IAggregateRootMapping<T> : IAggregateDefinition where T : AggregateRoot { IEnumerable<Expression<Func<T, object>>> IncludeDefinitions { get; } } public abstract class AggregateRootMapping<T
public interface IAggregateRootMapping<T> : IAggregateDefinition where T : AggregateRoot
{
IEnumerable<Expression<Func<T, object>>> IncludeDefinitions { get; }
}
public abstract class AggregateRootMapping<T> : IAggregateRootMapping<T> where T : AggregateRoot
{
public abstract IEnumerable<Expression<Func<T, object>>> IncludeDefinitions { get; }
}
public class OrderAggregateRootMapping : AggregateRootMapping<Order>
{
public override IEnumerable<Expression<Func<Order, object>>> IncludeDefinitions
{
get
{
return new Expression<Func<Order, object>>[] {
order => order.Supplier
};
}
}
}
公共接口IAggregateRootMapping:IAggregateDefinition其中T:AggregateRoot
{
IEnumerable包含定义{get;}
}
公共抽象类AggregateRootMapping:IAggregateRootMapping,其中T:AggregateRoot
{
公共抽象IEnumerable包含定义{get;}
}
公共类OrderAggregateRootMapping:AggregateRootMapping
{
公共重写IEnumerable IncludeDefinitions
{
得到
{
返回新表达式[]{
订单=>订单.供应商
};
}
}
}
我在另一个类中使用这些:
public class Repository<TAggregateRoot> : IRepository<TAggregateRoot> where TAggregateRoot : AggregateRoot
{
private readonly AggregateRootMapping<TAggregateRoot> _aggregateRootMapping;
public Repository(AggregateRootMapping<TAggregateRoot> aggregateRootMapping)
{
_aggregateRootMapping = aggregateRootMapping;
}
Do something...
}
公共类存储库:IRepository其中TAggregateRoot:AggregateRoot
{
私有只读AggregateRootMapping\u AggregateRootMapping;
公共存储库(AggregateRotMapping AggregateRotMapping)
{
_aggregateRootMapping=aggregateRootMapping;
}
做点什么。。。
}
如何使用ASP.NET Core的依赖项注入,以便在运行时注入匹配的类?
例如,如果AggregateRoot类型类的顺序大于存储库类的顺序,则应注入OrderAggregateRootMapping类。
如何使用.NET Core中Startup类的ConfigureServices中的ServiceCollection来完成此任务?默认情况下的依赖项注入非常基本。如果要开始基于泛型连接规则,则需要使用不同的实现 但是,如果您愿意一个接一个地编写依赖项,那么您所追求的仍然是可能的 在Startup.cs中
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<AggregateRootMapping<Order>, OrderAggregateRootMapping>();
services.AddScoped<Repository<Order>>();
// Add framework services.
services.AddMvc();
}
ValuesController随后将接收存储库
的实例,该实例将使用OrderAggregateRootMapping创建
[Route("api/[controller]")]
public class ValuesController : Controller
{
private Repository<Order> _repository;
public ValuesController(Repository<Order> repository)
{
_repository = repository;
}
}