3

I have following interfaces, abstract classes etc.

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

I use those in another class like this:

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

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

How do I use the dependency injection of ASP.NET Core so that on runtime the matching class is injected? For example if the AggregateRoot type class is Order than for the Repository class the OrderAggregateRootMapping class should be injected. How do I use the ServiceCollection in ConfigureServices of the Startup class in .NET Core to accomplish this?

1 Answer 1

1

The dependency injection that comes by default is very basic. If you want to start wiring up rules based on generics, you will need to use a different implementation.

But, what you're after is still possible if you're willing to code the dependencies one by one.

In your Startup.cs

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

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

And then you can use your Repository class by injecting it into a controller, for example.

In ValuesController.cs

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

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

ValuesController will then receive an instance of Repository<Order> which will have been created with a OrderAggregateRootMapping.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.