2017-02-23 153 views
3

我有以下接口,抽象類等高級依賴注入在ASP.NET核心

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 
      }; 
     } 
    } 
} 

我用那些在另一類是這樣的:

public class Repository<TAggregateRoot> : IRepository<TAggregateRoot> where TAggregateRoot : AggregateRoot 
{ 
    private readonly AggregateRootMapping<TAggregateRoot> _aggregateRootMapping; 

    public Repository(AggregateRootMapping<TAggregateRoot> aggregateRootMapping) 
    { 
     _aggregateRootMapping = aggregateRootMapping; 
    } 
Do something... 
} 

如何使用依賴注入的ASP.NET核心,以便在運行時匹配類被注入? 例如,如果AggregateRoot類型類是Order,而不是Repository類,則應該注入OrderAggregateRootMapping類。 如何在.NET Core的啓動類的ConfigureServices中使用ServiceCollection來完成此操作?

回答

1

默認情況下的依賴注入非常基本。如果你想開始基於泛型的規則,你需要使用不同的實現。

但是,如果您願意一個接一個地編寫依賴關係,您仍然可以繼續使用。

在你Startup.cs

public void ConfigureServices(IServiceCollection services) 
{ 
    services.AddScoped<AggregateRootMapping<Order>, OrderAggregateRootMapping>(); 
    services.AddScoped<Repository<Order>>(); 

    // Add framework services. 
    services.AddMvc(); 
} 

然後你就可以通過將其注入控制器,例如使用Repository類。

在ValuesController.cs

[Route("api/[controller]")] 
public class ValuesController : Controller 
{ 
    private Repository<Order> _repository; 

    public ValuesController(Repository<Order> repository) 
    { 
     _repository = repository; 
    } 
} 

ValuesController然後將收到的,這將已經用OrderAggregateRootMapping創建Repository<Order>一個實例。