I have an ASP.NET web application which until now has been using an Autofac configuration class which has specified an InstancePerRequest()
for services in the application.
Since then, I have created a new console application in the same solution which will be responsible for running automated job processes. Since I can't use the InstancePerRequest configuration for my console application, then I need to make a change to my configuration. Ideally, I don't want to copy and paste all the configuration into my JobRunner application and use the 'InstancePerLifetimeScope()
' configuration there.
Is there a better solution where I can largely use the same configuration to serve both projects? Perhaps there is a way to override the configuration for my Job Runner application but without having to specify a change in scope for every single service?
Although
InstancePerLifetimeScope
andInstancePerRequest
often have the same bahviour, they definitely have different intentions. I'd avoid usingInstancePerLifetimeScope
as a drop-in replacement, as it's easy to create unintended side-effects. For example, if you have a service that you had intended to only live for the duration of a web request, and all of a sudden it lives for the duration of you application (since it unintentionally resolved from the root scope).This effect would be worse inside your job runner, especially if you're not creating your own lifetime scopes - in this scenario, everything will live in the root scope, which means that one job will be sharing instances of a service with every other job that has a dependency on it.
Under the covers,
InstancePerRequest()
actually just delegates toInstancePerMatchingLifetimeScope()
with a well-known lifetime scope tag (which you can get fromMatchingScopeLifetimeTags.RequestLifetimeScopeTag
). So, one way you could achieve what you're asking is you could just cut-out the middle-man... for example, you could change your Autofac modules to take the lifetime scope tag as a constructor parameter:Now, when you're building your container from the web, you need to supply the well-known lifetime scope tag:
For your job runner, you can now mimic this behaviour, with a lifetime scope tag of your very own!
(I'm assuming here that each of your jobs implements an interface, let's say it looks like this):
Now you just need to run the jobs in their own lifetime scope, using the tag you just made up, e.g.: