Reputation: 1675
I have a windows service which keep on looping until it stopped. There is a thread interval of 15 second after each loop. I am using unity container to resolve an object as shown below:
var processes = ProcessConfigurationSection.GetProcesses();
while (!_stopped)
{
try
{
foreach (var process in processes)
{
var worker = new Worker(DiContainer.UnityContainer.Resolve<IProcessDao>());
worker.RunProcess(process.Name, process.StoredProcedure, process.BatchSize);
}
Thread.Sleep(_interval);
}
catch (Exception ex)
{
Log.LogEvent(...);
}
}
Should I create an instance of the worker (and resolve the object) inside the while loop or should it be outside the while loop for performance benefit? Also, is there a chance of memory leak for either of this approach?
Upvotes: 1
Views: 2003
Reputation: 172716
You should typically define a scope 'per request'. For a web application this would typically be a scope that lasts for the lifetime of the web request. For a Windows service application however there are still requests, only you have to decide what you see as request. Each RunProcess
call could be a single request (thus single scope) or processing the whole batch of processes
can be seen as a single request.
You shouldn't define this scope outside the loop because a scoped lifestyle would typically implement things like a unit of work implementations that get reused throughout the request. For instance Entity Framework's DbContext
is a unit of work. You wouldn't want to reuse the same DbContext
for the lifetime of the application, because when an operation fails, you could corrupt the DbContext
and therefore corrupt the complete application.
With Unity scoping is implemented using child containers. You should wrap your request with the following:
using (var child =
DiContainer.UnityContainer.CreateChildContainer())
{
var worker = new Worker(child.Resolve<IProcessDao>());
worker.RunProcess(process.Name, process.StoredProcedure,
process.BatchSize);
}
Or perhaps the using (var child
should wrap the foreach
. That is something you have to decide.
Upvotes: 1