I have an .net microservice that has a Service A which has an InstancePerLifetimeScope. Service A is injected into MessageService(singleton service).
public class MessageService
{
private readonly ServiceA serviceA;
public MessageService(ServiceA serviceA)
{
this.serviceA = serviceA;
}
public void ProcessItem(ItemClass item)
{
serviceA.Proccess(item);
}
}
In this way ServiceA is becoming a singleton by any thread that calls it. To achieve InstancePerLifetimeScope I would have:
public class MessageService
{
private readonly IContainer container;
public MessageService(IContainer container)
{
this.container = container;
}
public void ProcessItem(ItemClass item)
{
using (var scope = container.BeginLifetimeScope())
{
scope.Resolve<ServiceA>().Proccess(item);
}
}
}
Is this good practice? I read that this is service locator pattern and is considered an antipattern. Also passing container directly into a service as injectable is not the best thing.
public class ServiceAFactory
{
private readonly IContainer container;
public ServiceAFactory(IContainer container)
{
this.container = container;
}
public IServiceA swapsService CreateService()
{
using (var scope = container.BeginLifetimeScope())
{
return scope.Resolve<IServiceA>();
}
}
}