Reputation: 2083
I'm testing a small console application which will be used to display information based on a Quartz queue and I'm struggling to the the dependency to resolve within a reference assembly.
My console application references an EventData class, which has a dependency on IUtilities, within an assembly called App.Monitor, it's partial'ed as the base is code generated, and we're adding these properties / methods to the class for specific reasons...
public partial class EventData
{
private readonly IUtilities _utilities;
[JsonIgnore]
public DateTime? DateStamp => _utilities?.Epoch(Timestamp);
[JsonIgnore]
public EventType EventType =>
(EventType)EventType.Parse(typeof(EventType), (CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Event)));
public EventData(IUtilities utitlies)
{
_utilities = utitlies;
}
}
In my console application I set up .net core dependency injection per various examples on the net, code for reference:
public IServiceProvider BuildDependencies()
{
services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
services.AddTransient<IUtilities, Utilities>();
return services.BuildServiceProvider();
}
Then somewhere in the console application, I'm doing a call that should initiate this dependency in utilities, which it doesn't do, IUtilities is always NULL:
provider.GetRequiredService<IUtilities>(); // thought this would fix it...
var list = JsonConvert.DeserializeObject<List<QuartzJobs>>(json);
var stamp = list[0].EventData.DateStamp;
Update
QuartzJobs (code generated)
public class QuartzJobs
{
[JsonProperty("event-data")]
public EventData EventData { get; set; }
}
EventData (code generated)
public partial class EventData
{
[JsonProperty("timestamp")]
public double Timestamp { get; set; }
}
EventData (partial'ed with custom logic)
public partial class EventData
{
private readonly IUtilities _utilities;
[JsonIgnore]
public DateTime? DateStamp => _utilities?.Epoch(Timestamp);
[JsonIgnore]
public EventType EventType =>
(EventType)EventType.Parse(typeof(EventType), (CultureInfo.CurrentCulture.TextInfo.ToTitleCase(Event)));
public EventData(IUtilities utitlies)
{
_utilities = utitlies;
}
}
Upvotes: 1
Views: 64
Reputation: 247153
In the console you would need to take over the role of the framework and get the dependency and call the desired member
var utility = provider.GetRequiredService<IUtilities>();
var list = JsonConvert.DeserializeObject<List<QuartzJobs>>(json);
var stamp = utility?.Epoch(list[0].EventData.Timestamp);
That is because the container/provider is not the one resolving the EventData
, so nothing is being injected.
Upvotes: 1