Ninject - In what scope DbContext should get binded when RequestScope is meaningless? - multithreading

In an MVC / WebAPI environment I would use InRequestScope to bind the DbContext.
However, I am now on a Console application / Windows service / Azure worker role (doesn't really matter, just there's no Web request scope), which periodically creates a number of Tasks that run asynchronously. I would like each task to have its own DbContext, and since tasks run on their own thread, I tried binding DbContext using InThreadScope.
Unfortunately, I realize that the DbContext is not disposed when a task is finished. What actually happens is, the thread returns to the Thread Pool and when it is assigned a new task, it already has a DbContext, so DbContexts stay alive forever.
Is there a way InThreadScope can be used here or should I use some other scope? How can ThreadScope be used when threads are returning from ThreadPool every now and then?

If you decide to go on with custom scope, the solution is:
public sealed class CurrentScope : INotifyWhenDisposed
{
[ThreadStatic]
private static CurrentScope currentScope;
private CurrentScope()
{
}
public static CurrentScope Instance => currentScope ?? (currentScope = new CurrentScope());
public bool IsDisposed { get; private set; }
public event EventHandler Disposed;
public void Dispose()
{
this.IsDisposed = true;
currentScope = null;
if (this.Disposed != null)
{
this.Disposed(this, EventArgs.Empty);
}
}
}
Binding:
Bind<DbContext>().To<MyDbContext>().InScope(c => CurrentScope.Instance)
And finally:
using (CurrentScope.Instance)
{
// your request...
// you'll get always the same DbContext inside of this using block
// DbContext will be disposed after going out of scope of this using block
}

Related

how to do something when liferay module stop

i am making cron job like loop to do something using new thread.
when module stop, this thread keeps running, so when i deployed updated module, i'm afraid it will make duplicate thread doing similar task
#Component(immediate = true, service = ExportImportLifecycleListener.class)
public class StaticUtils extends Utils{
private StaticUtils() {}
private static class SingletonHelper{
private static final StaticUtils INSTANCE = new StaticUtils();
}
public static StaticUtils getInstance() {
return SingletonHelper.INSTANCE;
}
}
public class Utils extends BaseExportImportLifecycleListener{
public Utils() {
startTask();
}
protected Boolean CRON_START = true;
private void startTask() {
new Thread(new Runnable() {
public void run() {
while (CRON_START) {
System.out.println("test naon bae lah ");
}
}
}).start();
}
#Deactivate
protected void deactivate() {
CRON_START = false;
System.out.println(
"cron stop lah woooooooooooooooooy");
}
}
i'm using liferay 7
I have populated task that i store from db, so this thread is checking is there a task that it must do, then if it exist execute it.
I'm quite new in osgi and liferay. i've try to use scheduler and failed and also exportimportlifecycle listener but dont really get it yet
think again: Do you really need something to run all the time in the background, or do you just need some asynchronous processing in the background, when triggered? It might be better to start a background task as a one-off, that automatically terminates
Liferay provides an internal MessageBus, that you can utilize to listen to events and implement background processing, without the need for a custom thread
You're in the OSGi world, so you can utilize #Activate, #Modified, #Deactivate (from org.osgi.service.component.annotations) or use a org.osgi.framework.BundleActivator.
But, in general, it's preferable if you don't start your own thread

Allow only one user to access a page at a time in struts application

Having an huge customers profile page if two or more users start using same page and start editing big change will happen in my database so planing to implement Threads concept where only one user can use that customer page
i'm aware about threads concept but confused how to implement it
hope i need to use Singleton class as well
Any suggestion or Logic's will be helpful
I'm using Struts,Hibernate frame work
You may use application context to store a flag variable. Action will use its value to allow only one simultaneous execution.
public class TestAction extends ActionSupport implements ApplicationAware {
private static final String APP_BUSY_KEY = "APP_BUSY";
Map<String, Object> map;
#Override
public void setApplication(Map<String, Object> map) {
this.map = map;
}
#Override
public String execute() throws Exception {
if (map.containsKey(APP_BUSY_KEY)) {
return ERROR;
} else {
map.put(APP_BUSY_KEY, "1");
try {
// action logic here
} finally {
map.remove(APP_BUSY_KEY);
}
return SUCCESS;
}
}
}
If you plan to implement similar logic for two requests (lock after displaying values and release lock after submitting new values) then logic will be more complex and you will also need to handle lock release after timeout.

Current URL from PreApplicationStart

I am using StructureMap.MVC5 which relies on the PreApplicationStart method to register an HttpModule and initialize the IoC container. Is it possible to get the server name the page is executing on at this point so that I can set an environment specific property in the IoC initialization?
I was able to resolve this issue by moving the IoC initialization to the Application_BeginRequest method, where the HttpContext has already been set. In order to ensure that the IoC container was not reinitialized on each call to Application_BeginRequest, I was able to use a mutex block, thus negating the need to move this code to somewhere earlier in the page lifecycle.
public class FirstInitialization
{
private static Object s_lock = new Object();
public static string URL { get; protected set; }
// Initialise only on the first request
public static string Initialize(HttpContext context)
{
if (string.IsNullOrEmpty(URL))
{
lock (s_lock)
{
if (string.IsNullOrEmpty(URL))
{
URL = HttpContext.Current.Request.Url.AbsoluteUri;
}
DependencyResolver.SetResolver(IoC.GetDependencyResolver(URL));
}
}
return URL;
}
}

Entity Framework Context on multiple threads

I've seen so many questions similar to mine, but no answers that quite seem to apply to my situation.
My ASP.NET MVC app with EF 6 Code first and Unity has a web service that adds something to the database, then fires off another thread that adds more stuff to the database. The reason for using the other thread is to return the original request as quickly as possible. The context class is obtained using the Unity container RegisterType().
I've got lots of repository classes all using the same context, so to make sure they get the same instance I could use the PerRequestLifetimeManager in my Unity container, and that's fine for the http request threads but that the other threads can't use the context returned by the PerRequestLifetimeManager because this is only valid on the original http request thread.
So, I can use the PerThreadLifetimeManager. This is great because now the main request thread and the other thread it kicks off get the same instance of the context returned by Unity. The trouble is that so do other requests if they get given the same thread, so this is no good either.
So how can I configure things so that the request threads get their own PerRequest Lifetime Manager created context, and other threads get a different context?
The issue is made a little more difficult by the fact that the new thread calls other classes that need to use a context instance. However, these other classes can be used from the main request thread or the new thread, so grabbing a context instance when the thread is started and then passing it around will be tricky.
Thanks in advance
No takers then...
I'm going to have a go at answering my own question, but could do with some thoughts on my approach.
So I can't use the PerRequestLifetimeManager because worker threads can't use the context that this returns, but I can't use the PerThreadLifetimeManager because the context can last the lifetime of several HTTP requests. This class attempts to provide the best of both worlds.
/// <summary>
/// For the context class the PerRequestLifetimeManager is the most suitable lifetime manager,
/// but this doesn't work when a new worker thread is started as this needs to access the context.
/// The PerThreadLifetimeManager is no good either as the context can last for more than on request.
/// This class attempts to give the best of both worlds: per request lifetime management for HTTP requests
/// and thread storage for worker threads.
/// </summary>
public class PerRequestOrThreadLifetimeManager : PerRequestLifetimeManager, IDisposable
{
private const string threadDataSlotName = "PerRequestOrThreadLifetimeManager";
public override object GetValue()
{
if (System.Web.HttpContext.Current != null)
{
return base.GetValue();
}
else
{
return getManagedObject();
}
}
public override void RemoveValue()
{
throw new NotImplementedException();
}
public override void SetValue(object newValue)
{
if (System.Web.HttpContext.Current != null)
{
base.SetValue(newValue);
}
else
{
Thread.SetData(Thread.GetNamedDataSlot(threadDataSlotName), newValue);
}
}
private object getManagedObject()
{
return Thread.GetData(Thread.GetNamedDataSlot(threadDataSlotName));
}
public void Dispose()
{
try
{
IDisposable obj = getManagedObject() as IDisposable;
if (obj != null)
{
obj.Dispose();
obj = null;
}
}
catch { }
}
}

Running windows service in separate thread and use autofac for DI

I'm trying to create a long running windows service, so I need to run the actual worker class on a separate thread, to avoid the "service did not respond in a timely fashion" error when I right click and select start in Windows Service Manager.
The worker class ("NotificationProcess") has a whole raft of dependencies and I'm using Autofac to satisfy these.
I'm really not sure how to set up Autofac for the worker class. At the moment I'm getting errors telling me that the DbContext has been disposed when I go to use it in the "Execute" method of the worker class.
I guess I'm looking for how to write a windows service and use a new thread for the worker class with dependencies satisfied by autofac.
I've googled and can't find any examples of this.
Any suggestions would be awesome.
Here's what I've got so far...
Program.cs:
static class Program
{
static void Main()
{
using (var container = ServiceStarter.CreateAutoFacContainer())
{
var service = container.Resolve<NotificationService>();
if (Environment.UserInteractive)
{
service.Debug();
}
else
{
ServiceBase.Run(container.Resolve<NotificationService>());
}
}
The Service class:
public partial class NotificationService : ServiceBase
{
private NotificationProcess _app;
readonly ILifetimeScope _lifetimeScope;
public NotificationService(ILifetimeScope lifetimeScope)
{
_lifetimeScope = lifetimeScope;
InitializeComponent();
}
protected override void OnStart(string[] args)
{
_app = _lifetimeScope.Resolve<NotificationProcess>();
_app.Start();
}
The worker class:
public class NotificationProcess
{
private Thread _thread;
private readonly IBankService _bankService;
private readonly IRateService _rateService;
private readonly IEmailService _emailService;
private readonly IRateChangeSubscriberService _rateChangeSubscriberService;
private readonly IRateChangeNotificationService _rateChangeNotificationService;
private readonly ILogManager _logManager;
public NotificationProcess(IBankService bankService, ILogManager logManager, IRateService rateService, IEmailService emailService,
IRateChangeSubscriberService rateChangeSubscriberService, IRateChangeNotificationService rateChangeNotificationService)
{
_bankService = bankService;
_rateService = rateService;
_emailService = emailService;
_rateChangeSubscriberService = rateChangeSubscriberService;
_rateChangeNotificationService = rateChangeNotificationService;
_logManager = logManager;
}
public void Start()
{
_thread = new Thread(new ThreadStart(Execute));
_thread.Start();
}
public void Execute()
{
try
{
var rateChangeToNotify = _rateService.GetRateChangesForNotification();
foreach (var rateChange in rateChangeToNotify)
{
//do whatever business logic.....
}
}
}
The answer is actually simple: use scoping! You should do the following:
Register all services (such as DbContext) that should live for the duration of a request or action with the LifetimeScope lifestyle. You'll usually have a timer in your windows service. Each 'pulse' can be considered a request.
On the beginning of each request begin a lifetime scope.
Within that scope, resolve the root object from the object graph and call its method.
Dispose the scope.
In your case that means you need to change your design, since NotificationService is resolved once and its dependencies are reused on another thread. This is a no-no in dependency injection land.
Here's an alternative design:
// This method is called on a background thread
// (possibly in a timely manner)
public void Run()
{
try
{
using (var scope = container.BeginLifetimeScope())
{
var service = scope.Resolve<NotificationService>();
service.Execute();
}
}
catch (Exception ex)
{
// IMPORTANT: log exception.
// Not logging an exception will leave us in the dark.
// Not catching the exception will kill our service
// because we run in a background thread.
}
}
Using a lifetime scope allows you to get a fresh DbContext for every request and it would even allow you to run requests in parallel (with each request its own DbContext).

Resources