Reputation: 518
I have a problem in .net core that I need to resolve the dependency based on the value I am getting from the API.
Interface
public interface IBookingSettingsDetails
{
void GetSettings();
}
Class A
public class ScheduleSettingsA: IBookingSettingsDetails
{
public void GetSettings() {}
}
Class B
public class ScheduleSettingsB: IBookingSettingsDetails
{
public void GetSettings() {}
}
Resolver under startup.cs file is
services.AddTransient<Func<int, IBookingSettingsDetails>>(serviceProvider => conferencingType =>
{
switch (conferencingType)
{
case 1:
return serviceProvider.GetService<ScheduleSettings>();
case 2:
return serviceProvider.GetService<WebexSettings>();
default:
throw new InvalidOperationException();
}
});
Whenever I am trying to resolve dependency from the controller then I am always getting null in the resolver.
public class VideoConferenceController : ControllerBase
{
private readonly Func<int, IBookingSettingsDetails> _serviceAccessor;
public VideoConferenceController(Func<int, IBookingSettingsDetails> serviceAccessor)
{
_serviceAccessor = serviceAccessor;
}
[HttpGet]
[Route("getRandom")]
public void getRandom(int conferenceType)
{
var service= _serviceAccessor(conferenceType);
service.GetSettings();
}
}
I want to resolve the dependency based on the parameter specified in the function. I don't want to use any third-party library like Unity. Can it be done using the above approach?
Upvotes: 0
Views: 1525
Reputation: 518
To resolve this issue. I just added
services.AddTransient<ScheduleSettingsA>();
services.AddTransient<ScheduleSettingsB>();
in the startup file.
Upvotes: 1