How to Subscribe to a Constructor in vNext Dependency Injection
I am experimenting with a one-off vNext app. What I am trying to do is create a dummy class called "DataService" that will return some data and then create objects that use DI to accept the IDataService parameter as a constructor.
So, my IDataService / DataService definitions are:
public interface IDataService
{
DateTime Created { get; }
}
public class DataService : IDataService
{
private DateTime created = DateTime.Now;
public DateTime Created
{
get { return created; }
}
}
In my startup class, I register this as a singleton:
public void Configure(IApplicationBuilder app)
{
app.UseServices(services =>
{
services.AddSingleton<Data.IDataService, Data.DataService>();
});
And in the class I created, I add the IDataService interface as a constructor dependency:
internal class Constraint : IRouteConstraint
{
private readonly IDataService _dataService;
public Constraint (IDataService dataService)
{
_dataService = dataService;
}
public bool Match(....)
{
//call dataservice for match
}
}
The class here with constructor dependencies is IRouteConstraint which I am trying to use to get dynamic routes in MVC - the last part of the launcher class code looks like this:
app.UseMvc(routes => {
routes.MapRoute(name: "TestRoute", template: "{*constraints}", defaults: new { controller = "Test", action = "Index" }, constraints: new { constraint = new Constraint() }); //<--- how to construct using DI?
});
The problem is that the Constraint () class cannot be instantiated because the constructor is missing. All examples show a controller using DI, and the instantiation of Controller classes is handled by MVC, so this is a part of "automagic" that we don't see at first glance.
So my question is:
- How do I instantiate a 'Constraint' object so that the DI provides an implementation of the DataService syntax?
- Is my problem because I am trying to use this in the Configure method in the UseMvc method, or is my problem more fundamental?
I suppose I am missing some way to make DI act like a factory object to provide my objects rather than declaratively creating them.
source to share
If you want to resolve your constraint through Dependency Injection, you need to register it, first:
services.AddTransient<Constraint>();
Once you have the IApplicationBuilder, you can access services directly:
app.ApplicationServices.GetRequiredService<Constraint>();
Of course, if you don't want to add your type Constraint
to the list of services, you can still access IDataService
the same way.
It is supposed to be using Microsoft.Framework.DependencyInjection;
declared at the top of your Startup; given your different syntax, I believe you are doing this.
source to share