I have the following scenario:
I got a service ICompanyDocumentsService with a single implementation CompanyDocumentsServicewhich I register in my Startup class:
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<ICompanyDocumentService, CompanyDocumentService>();
}
I need this service in many places, and it doesn't bother me using DI in Constructor. However, there is one place where I need it injected in a Method (or probably in a property would be even better):
public abstract class CompanyDocumentBase
{
public abstract object GetAllProperties(Employee employee, string properties,
CompanyDocumentReferenceData documentReferenceData);
// blah, blah, lots of Formatting Methods
private CompanyDocumentService CompanyDocumentService { get; set; } // **inject service here**
public string GetFormattedEmployeeIndividualEmploymentAgreementNumber(Employee employee,
ICompanyDocumentService companyDocumentService = null) // **optional because
//inherited class doesn't need to know anything about this service, it concerns only it's result**
{
companyDocumentService = CompanyDocumentService;
var test =
companyDocumentService.GetEmloyeeIndividualEmploymentAgreementNumber(employee.Id);
return string.Empty;
}
}
There are many classes inheriting CompanyDocumentBase which are only concerned in it's method results, as mentioned above, that's why that parameter is optional, and that's why I don't need injecting DI in constructor, thus the inheriting classes won't be needing that.
public class JobDescriptionCompanyDocument : CompanyDocumentBase
{
public override object GetAllProperties(Employee employee,
string properties, CompanyDocumentReferenceData documentReferenceData)
{
var document = JsonConvert.DeserializeObject<JobDescriptionModel>(properties);
document.IndividualEmploymentAgreementNumber = GetEmployeeIndividualEmploymentAgreementNumber(employee);
return document;
}
}
Is there any simple way to achieve this? Preferable without needing to install a separate library like Unity or Autofac.
Ideal it would be to somehow get the instance of CompanyDocumentsService directly into that property, something like:
private CompanyDocumentService CompanyDocumentService => Startup.Services.blah that instance
FromServices?