How and where to dispose dbcontext using unity PerRequestLifetimeManager - c#

I am using unity IOC to inject the dbcontext in the relevant classes in a Web API. I am using custom lifetime manager as shown below:
public class PerRequestLifetimeManager : LifetimeManager
{
private readonly object key = new object();
public override object GetValue()
{
if (HttpContext.Current != null &&
HttpContext.Current.Items.Contains(key))
return HttpContext.Current.Items[key];
else
return null;
}
public override void RemoveValue()
{
if (HttpContext.Current != null)
HttpContext.Current.Items.Remove(key);
}
public override void SetValue(object newValue)
{
if (HttpContext.Current != null)
HttpContext.Current.Items[key] = newValue;
}
}
This is injected in global.asax as this:
// context - one context per http request
container.RegisterType(new PerRequestLifetimeManager());
In dbcontext class we have this:
public class BudgetControlDbContext : DbContext, IBudgetControlDbContext
{
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
this._isDisposed = true;
}
public bool IsDisposed
{
get { return this._isDisposed; }
}
}
Question:
Now how to dispose the dbcontext and where that code should be?

Related

Initialize Shell with ViewModel after all modules loaded in Prism 6

The ViewModel (set via AutoWireViewModel="True") of my Shell / MainWindow requests a dependency which gets loaded in a module at startup using the ConfigurationModuleCatalog.
Because the Shell is initialzed before the modules, the DI container obviously can't resolve it, so the application crashes.
public class MainWindowViewModel : BindableBase
{
// Cannot resolve IService
public MainWindowViewModel(IService service)
{
}
}
I already tried the two approaches of this post, but both didn't worked.
I tried it this way:
public interface IShellService
{
int NumberOfLoadedModules { get; }
void FlagModuleAsLoaded();
}
public class ShellService : IShellService
{
private readonly IModuleCatalog _moduleCatalog;
public ShellService(IModuleCatalog moduleCatalog)
{
_moduleCatalog = moduleCatalog;
}
public int NumberOfLoadedModules { get; private set; }
public void FlagModuleAsLoaded()
{
NumberOfLoadedModules++;
if (NumberOfLoadedModules != _moduleCatalog.Modules.Count())
return;
InitializeShell();
}
private static void InitializeShell()
{
Application.Current.MainWindow.Show();
}
}
internal class Bootstrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
return null;
}
protected override void InitializeShell()
{
}
protected override void ConfigureContainer()
{
base.ConfigureContainer();
Container.RegisterInstance<IShellService>(new ShellService(ModuleCatalog), new ContainerControlledLifetimeManager());
}
protected override IModuleCatalog CreateModuleCatalog()
{
return new ConfigurationModuleCatalog();
}
}
Usage
public abstract class ModuleBase : IModule
{
private readonly IShellService _shellService;
protected ModuleBase(IShellService shellService)
{
_shellService = shellService;
}
public void Initialize()
{
InitializeInternal();
FlagAsLoaded();
}
public abstract void InitializeInternal();
public void FlagAsLoaded()
{
_shellService.FlagModuleAsLoaded();
}
}
public class FooModule : ModuleBase
{
IUnityContainer _container;
public MusicUIModule(IUnityContainer container, IShellService shellService) : base(shellService)
{
_container = container;
}
public override void InitializeInternal()
{
_container.RegisterType<IService, Service>();
}
}
It starts counting the modules and then the application crashes because of the same reason.
If the approach above isn't fitting for my purpose, how could that problem be solved?
Thanks!
I tried to implement Haukinger's suggestion and did it this way which works just fine:
// Factory --------------------------------------------------------
public interface IDependencyFactory
{
IService GetService();
}
public class DependencyFactory : IDependencyFactory
{
private readonly IUnityContainer _container;
public DependencyFactory(IUnityContainer container)
{
_container = container;
}
public IService GetService()
{
return _container.Resolve<IService>();
}
}
// PubSubEvent ------------------------------------------------------
public class AllModulesLoaded : PubSubEvent
{
}
// Bootstrapper -----------------------------------------------------
internal class Bootstrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
return Container.Resolve<MainWindow>();
}
protected override void InitializeShell()
{
Application.Current.MainWindow.Show();
}
protected override void InitializeModules()
{
base.InitializeModules();
// Publishing event to tell subscribers that the modules are loaded
var eventAggregator = Container.Resolve<IEventAggregator>();
eventAggregator?.GetEvent<AllModulesLoaded>().Publish();
}
protected override void ConfigureContainer()
{
base.ConfigureContainer();
// ...
Container.RegisterType<IDependencyFactory, DependencyFactory>();
}
protected override IModuleCatalog CreateModuleCatalog()
{
return new ConfigurationModuleCatalog();
}
}
// ViewModel ---------------------------------------------------------
public class MainWindowViewModel : BindableBase
{
private IService _service;
private readonly IEventAggregator _eventAggregator;
private readonly IDependencyFactory _dependencyFactory;
public MainWindowViewModel(IEventAggregator eventAggregator, IDependencyFactory dependencyFactory)
{
_eventAggregator = eventAggregator;
_dependencyFactory = dependencyFactory;
_eventAggregator.GetEvent<AllModulesLoaded>().Subscribe(OnAllModulesLoaded);
}
private void OnAllModulesLoaded()
{
var service = _dependencyFactory.GetService();
if (service != null)
_service = service ;
_eventAggregator.GetEvent<AllModulesLoaded>().Unsubscribe(OnAllModulesLoaded);
}
}
I'd hide the dependency of the shell behind a factory/provider and then create/fetch it when the last module is loaded. Your shell's view model subscribes to a AllModulesLoaded event that's fired from your bootstrapper's InitializeModules when base.InitializeModules returns to get notified that the dependency is available. Or the factory/provider subscribes to the event and the shell polls it, depending on how you want to use the dependency.

How to properly dispose objects: injected vs. owned

I have a question about disposing objects.
Consider this IDisposable class
public class MyClass : DisposableParentClass
{
private MyProp _prop;
public MyClass(MyProp prop)
{
_prop = prop;
}
public MyClass()
{
_prop = new MyProp();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_prop.Dispose();
}
base.Dispose(disposing);
}
}
On the first constructor, MyProp is injected. So MyClass is not the owner of the object. But on the second constructor, MyProp is created locally.
Should I always dispose MyProp, or should I check first if it is injected or not.
public class MyClass : DisposableParentClass
{
private MyProp _prop;
private bool _myPropInjected = false;
public MyClass(MyProp prop)
{
_prop = prop;
_myPropInjected = true;
}
public MyClass()
{
_prop = new MyProp();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (!_myPropInjected) { _prop.Dispose(); }
}
base.Dispose(disposing);
}
}
If your class should handle these two situations:
It is not the owner of the provided object, it should not dispose of it
It is the owner of the created object, it should dispose of it
Then yes, you need to have a mechanism that tells these two situations apart.
A common method (common to me anyway) is to use naming convention like this:
private MyProp _prop;
private bool _ownsProp = false;
ie. reverse the meaning of your flags, but this is details, your solution is just fine, and yes, you need to have a solution like this.
If you have a ton of these fields, where each must have its own bool field to handle this, it might be worth creating a helper class, such as this LINQPad program demonstrates:
void Main()
{
Injectable i1 = new Injectable();
Injectable i2 = new Injectable(new Injected("A"));
Injectable i3 = new Injectable(new Injected("A"), new Injected("B"));
Debug.WriteLine("dispose a and b");
i1.Dispose();
Debug.WriteLine("dispose b");
i2.Dispose();
Debug.WriteLine("no dispose");
i3.Dispose();
}
public class Injected : IDisposable
{
public Injected(string name) { Name = name; }
public string Name { get; set; }
public void Dispose() { Debug.WriteLine(Name + " disposed"); }
}
public class Injectable : IDisposable
{
private Ownable<Injected> _A;
private Ownable<Injected> _B;
public Injectable(Injected a, Injected b)
{
_A = Ownable.NotOwned(a);
_B = Ownable.NotOwned(b);
}
public Injectable(Injected a)
{
_A = Ownable.NotOwned(a);
_B = Ownable.Owned(new Injected("B"));
}
public Injectable()
{
_A = Ownable.Owned(new Injected("A"));
_B = Ownable.Owned(new Injected("B"));
}
public void Dispose()
{
_A.Dispose();
_B.Dispose();
}
}
public class Ownable<T> : IDisposable
where T : class
{
private readonly T _Instance;
private readonly Action _CleanupAction;
public Ownable(T instance, bool isOwned)
{
_Instance = instance;
if (isOwned)
{
IDisposable disposable = instance as IDisposable;
if (disposable == null)
throw new NotSupportedException("Unable to clean up owned object, does not implement IDisposable");
_CleanupAction = () => disposable.Dispose();
}
}
public Ownable(T instance, Action cleanupAction)
{
_Instance = instance;
_CleanupAction = cleanupAction;
}
public T Instance { get { return _Instance; } }
public void Dispose()
{
if (_CleanupAction != null)
_CleanupAction();
}
}
public static class Ownable
{
public static Ownable<T> Owned<T>(T instance)
where T : class
{
return new Ownable<T>(instance, true);
}
public static Ownable<T> Owned<T>(T instance, Action cleanupAction)
where T : class
{
return new Ownable<T>(instance, cleanupAction);
}
public static Ownable<T> NotOwned<T>(T instance)
where T : class
{
return new Ownable<T>(instance, false);
}
}
A different note can be made here either.
It depends on what is your MyClass is doing actually.
For example, if we are talking about a class that reads video stream from device, after applies some filters to it and writes data to a user specified file, where file writing is made by stream passed from the outside, say like this:
public class VideoProcessor : IDisposable {
private FileStream _videoFile = null;
private VideoProcessor() {}
//user specified FileStream
public VideoProcessor(FileStream fs) {_videoFile = fs;}
public void Dispose() {
_videoFile.Dispose(); //Dispose user passed FileStream
}
}
disposing passed stream object during dispose call, makes actually sence.
In other cases, yes, it's better to not destroy object, if you are not an owner of it. Leave it to the caller to decide when it is appropriate time to do that.

Best practice to handle memory leak for Static Field in C#

I am supposed to create a context object for the current instance of the user, and the code is
public class WorkoutContext {
protected static WorkoutContext mWorkoutContext ;
protected WorkOut mWorkOut;
protected WorkoutContext(WorkOut workout)
{
mWorkOut= workout;
}
public static WorkoutContext CreateContext(WorkOut workout))
{
if (mWorkoutContext == null)
{
mWorkoutContext = new WorkoutContext (form);
}
else
{
if (workout != mWorkoutContext.WorkOut)
{
mWorkoutContext = new WorkoutContext (workout);
}
}
return mWorkoutContext ;
}
}
In concurrent environment, for each user it is creating an instance for WorkOutContext but not release the instance after the request process completion. To Overcome this issue modified the CreateContext method as follow
public class WorkoutContext {
protected WorkoutContext mWorkoutContext ;
protected WorkOut mWorkOut;
protected WorkoutContext(WorkOut workout)
{
mWorkOut= workout;
}
public static WorkoutContext CreateContext(WorkOut workout))
{
return new WorkoutContext(workout);
}
}
Is there any other way to implement to have only one instance of WorkoutContext for the same WorkOut instance.
Try something like this:
public class WorkoutContext {
protected WorkOut mWorkOut;
private static Dictionary<WorkOut, WorkoutContext> dic = new ...;
private static object lockObj = new object();
protected WorkoutContext(WorkOut workout)
{
mWorkOut= workout;
}
public static WorkoutContext CreateContext(WorkOut workout)
{
lock(lockObj) {
if (dic.ContainsKey(workout))
return dic[workout];
var wc = new WorkoutContext(workout)
dic.Add(workout, wc);
return wc;
}
}
}

Implementing repository pattern

As per this tutorial on asp.net, it shows this code:
using System;
using ContosoUniversity.Models;
namespace ContosoUniversity.DAL
{
public class UnitOfWork : IDisposable
{
private SchoolContext context = new SchoolContext();
private GenericRepository<Department> departmentRepository;
private GenericRepository<Course> courseRepository;
public GenericRepository<Department> DepartmentRepository
{
get
{
if (this.departmentRepository == null)
{
this.departmentRepository = new GenericRepository<Department>(context);
}
return departmentRepository;
}
}
public GenericRepository<Course> CourseRepository
{
get
{
if (this.courseRepository == null)
{
this.courseRepository = new GenericRepository<Course>(context);
}
return courseRepository;
}
}
public void Save()
{
context.SaveChanges();
}
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
context.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
Do I have to write code every time I want add a new database table? For instance, if I wanted to add a StudentsRepository, I would have to do this (?):
private GenericRepository<Student> studentRepository;
public GenericRepository<Student> StudentRepository
{
get
{
if (this.studentRepository == null)
{
this.studentRepository = new GenericRepository<Student>(context);
}
return studentRepository;
}
}
What if my database has 50 tables? Do I have to write this code for all 50!?
The answer to your question is "yes", the unit of work should contain properties to access all possible repositories.
If it bothers you to write code, create a T4 template and let the class be generated automatically.

Implementing Dispose() with class derived from System.ComponentModel.Component

I made a class that derives from Component:
public class MyComponent: System.ComponentModel.Component
{
}
I saw that Visual Studio put this code in for me:
protected override void Dispose(bool disposing)
{
try
{
if (disposing && (components != null))
{
components.Dispose();
}
}
catch
{
throw;
}
finally
{
base.Dispose(disposing);
}
}
MyComponent has a member that is a DataSet and maybe there's some other members that implement IDisposable. What, if anything, do i need to modify with the Dispose() method to make sure things are cleaned up properly? Thanks for helping.
Change:
if (disposing && (components != null))
{
components.Dispose();
}
to be:
if (disposing && (components != null))
{
_dataset.Dispose();
components.Dispose();
}
Check any disposable member objects and dispose them if they are not null.
I came up with this class:
public class DisposableComponentWrapper : IComponent
{
private IDisposable disposable;
public DisposableComponentWrapper(IDisposable disposable)
{
this.disposable = disposable;
}
public DisposableComponentWrapper(IDisposable disposable, ISite site)
: this(disposable)
{
Site = site;
}
public void Dispose()
{
if (disposable != null)
{
disposable.Dispose();
}
if (Disposed != null)
{
Disposed(this, EventArgs.Empty);
}
}
public ISite Site { get; set; }
public event EventHandler Disposed;
}
and extension method to IContainer:
public static void Add(this IContainer container, IDisposable disposableComponent)
{
var component = (disposableComponent as IComponent);
if(component == null)
{
component = new DisposableComponentWrapper(disposableComponent);
}
container.Add(component);
}
Which might help those willing to enlist disposable resources to their forms.
Note: I'm not certain of the behaviour for IComponent.Disposed, MSDN doesn't say much about how it should be called in implementation of this interface, the documentation sounds like talking about client code registering to the event more than when it should be triggered by implementations of this interface.
Wrap the disposables in components and add them in the components collection. The generated implementation of the dispose pattern will dispose of them correctly.
public partial class MyComponent : System.ComponentModel.Component
{
private readonly System.Data.DataSet _dataSet;
public MyComponent(System.Data.DataSet dataSet)
{
_dataSet = dataSet ?? throw new System.ArgumentNullException(nameof(dataSet));
components.Add(new DisposableWrapperComponent(dataSet));
}
}
The DisposableWrapperComponent is defined thus:
using System;
using System.ComponentModel;
public class DisposableWrapperComponent : Component
{
private bool disposed;
public IDisposable Disposable { get; }
public DisposableWrapperComponent(IDisposable disposable)
{
Disposable = disposable ?? throw new ArgumentNullException(nameof(disposable));
}
protected override void Dispose(bool disposing)
{
if (disposed) return;
if (disposing)
{
Disposable.Dispose();
}
base.Dispose(disposing);
disposed = true;
}
}
Inspired by the answer by #smoothdeveloper.
If you need to be able to reset the data set, encapsulating the lifetime management in a property works quite well.
using System;
using System.ComponentModel;
using System.Data;
public partial class MyComponent : Component
{
private const string DataSetComponentName = "dataSet";
public DataSet DataSet
{
get => (DataSet)((DisposableWrapperComponent)components.Components[DataSetComponentName])
?.Disposable;
set
{
var lastWrapper = (DisposableWrapperComponent)components.Components[DataSetComponentName];
if (lastWrapper != null)
{
components.Remove(lastWrapper);
lastWrapper.Dispose();
}
if (value != null)
{
components.Add(new DisposableWrapperComponent(value), DataSetComponentName);
}
}
}
public MyComponent(DataSet dataSet)
{
DataSet = dataSet ?? throw new ArgumentNullException(nameof(dataSet));
}
}
I used this when implementing a Windows Service that creates a disposable object in OnStart and disposes of it in OnStop.

Categories

Resources