Here's my class:
public class TaskLogger : ITaskLogger
{
private readonly IDbConnection _dbConnection;
public TaskLogger(IDbConnection dbConnection)
{
_dbConnection = dbConnection;
}
public void LogTask(int clientId, string taskName)
{
_dbConnection.Execute("insert blah",{clientId,taskName}});
}
}
We use Windsor for DI.
Should TaskLogger be declared IDisposable, and dispose the IDbConnection?
No. Since the instance is passed to your class from the caller, the caller is responsible for disposing it. This is because your class should not assume it is the only consumer of this instance - there might be another class that uses the same connection but lives longer than your TaskLogger instance.
Your class should dispose the instances it creates itself.
Another approach would be to add a constructor public TaskLogger(IDbConnection dbConnection, bool closeConnection) and dispose the connection when the value passed in is true. This approach is used by some System.IO classes (although they do it the other way around and use leaveOpen - but for streams it is a different story because usually a stream will not be used by multiple instances at the same time).
Related
I've created a subclass of Microsoft.EntityFrameworkCore.DbContext (called AppContext) and I am creating an instance of AppContext in my test class.
I've added an empty constructor to AppContext to resolve a build error: CS1729 'AppContext' does not contain a constructor that takes 1 arguments. I can't figure out why I need to do this.
The parent class DbContext appears to have a constructor that takes a single argument of type Microsoft.EntityFrameworkCore.DbContextOptions. When I call the constructor for AppContext I'm passing an argument of type DbContextOptions<AppContext>.
AppContext:
using Microsoft.EntityFrameworkCore;
using OMSBackend.Models;
namespace OMSBackend
{
public class AppContext : DbContext
{
// A build error occurs if I comment out this constructor.
public AppContext(DbContextOptions options) : base(options)
{
}
public DbSet<User> Users { get; set; }
}
}
InMemoryDatabaseTestBase:
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
namespace OMSBackend.Tests.Unit
{
public abstract class InMemoryDatabaseTestBase : IDisposable
{
private DbContextOptions<AppContext> _contextOptions;
private SqliteConnection _connection;
protected InMemoryDatabaseTestBase()
{
_connection = OpenInMemorySqliteConnection();
_contextOptions = new DbContextOptionsBuilder<AppContext>()
.UseSqlite(_connection)
.Options;
}
public void Dispose()
{
_connection.Dispose();
}
protected AppContext CreateContext()
{
return new(_contextOptions);
}
private SqliteConnection OpenInMemorySqliteConnection() {
_connection = new SqliteConnection("Filename=:memory:");
_connection.Open();
return _connection;
}
}
}
(The using statements are present because I've disabled ImplicitUsings in my project.)
I'm new to C#, but it seems like I shouldn't need to override the constructor here. Is there something I've overlooked that would allow me to extend DbContext without overriding the constructor?
I've used these articles as a guide:
https://learn.microsoft.com/en-us/ef/core/testing/testing-without-the-database#sqlite-in-memory
https://www.meziantou.net/testing-ef-core-in-memory-using-sqlite.htm (GĂ©rald's SampleDbContext class also overrides the constructor, as I've had to do.)
A class doesn't automatically inherit a constructor from its base class. All constructors for a class, other than the default (parameterless) constructor, must be implemented in that class. You aren't actually overriding anything in that code. You are implementing a new constructor in your derived class and that invokes a constructor in the base class. A derived constructor will often invoke a base constructor with the same parameters but it doesn't have to do so.
If you haven't called a constructor, then the behaviour of accessing a member of a type wouldn't be well defined. So as a general rule that applies to all Object Oriented programming languages, when constructing a class you must first construct a valid instance of your base class.
The C# compiler will help you handle the common case of parameter-less constructors in a couple of ways.
if the base class has a parameter-less constructor, it will be called implicitly.
if you haven't provided any explicit constructors, the compiler will generate a parameter-less constructor for you.
My application is using 3 layers: DAL / Service / UL.
My typical DAL class looks like this:
public class OrdersRepository : IOrdersRepository, IDisposable
{
private IDbConnection _db;
public OrdersRepository(IDbConnection db) // constructor
{
_db = db;
}
public void Dispose()
{
_db.Dispose();
}
}
My service calls the DAL class like this (injecting a database connection):
public class ordersService : IDisposable
{
IOrdersRepository _orders;
public ordersService() : this(new OrdersRepository(new Ajx.Dal.DapperConnection().getConnection()))
{
}
public ordersService(OrdersRepository ordersRepo)
{
_orders = ordersRepo;
}
public void Dispose()
{
_orders.Dispose();
}
}
And then finally within my UI layer, this is how I access my service layer:
public class OrdersController : Controller, IDisposable
{
//
// GET: /Orders/
private ordersService _orderService;
public OrdersController():this(new ordersService())
{
}
public OrdersController(ordersService o)
{
_orderService = o;
}
void IDisposable.Dispose()
{
_orderService.Dispose();
}
}
This all works good. But as you can see, I am relying on IDisposable within every layer. UI disposes service object and then service object disposes DAL object and then DAL object disposes the database connection object.
I am sure there has to be a better way of doing it. I am afraid users can forget to dispose my service object (within UI) and I will end up with many open database connections or worse. Please advise the best practice. I need a way to auto-dispose my database connections OR any other unmanaged resources (files etc).
Your question comes back to the principle of ownership:
he who has ownership of the resource, should dispose it.
Although ownership can be transferred, you should usually not do this. In your case the ownership of the IDbConnection is transferred from the ordersService to the OrdersRepository (since OrdersRepository disposes the connection). But in many cases the OrdersRepository can't know whether the connection can be disposed. It can be reused throughout the object graph. So in general, you should not dispose objects that are passed on to you through the constructor.
Another thing is that the consumer of a dependency often can't know if a dependency needs disposal, since whether or not a dependency needs to be disposed is an implementation detail. This information might not be available in the interface.
So instead, refactor your OrdersRepository to the following:
public class OrdersRepository : IOrdersRepository {
private IDbConnection _db;
public OrdersRepository(IDbConnection db) {
_db = db;
}
}
Since OrdersRepository doesn't take ownership, IDbConnection doesn't need to dispose IDbConnection and you don't need to implement IDisposable. This explicitly moves the responsibility of disposing the connection to the OrdersService. However, ordersService by itself doesn't need IDbConnection as a dependency; it just depends on IOrdersRepository. So why not move the responsibility of building up the object graph out of the OrdersService as well:
public class OrdersService : IDisposable {
private readonly IOrdersRepository _orders;
public ordersService(IOrdersRepository ordersRepo) {
_orders = ordersRepo;
}
}
Since ordersService has nothing to dispose itself, there's no need to implement IDisposable. And since it now has just a single constructor that takes the dependencies it requires, the class has become much easier to maintain.
So this moves the responsibility of creating the object graph to the OrdersController. But we should apply the same pattern to the OrdersController as well:
public class OrdersController : Controller {
private ordersService _orderService;
public OrdersController(ordersService o) {
_orderService = o;
}
}
Again, this class has become much easier to grasp and it doesn't needs to dispose anything, since it doesn't has or took ownership of any resource.
Of course we just moved and postponed our problems, since obviously we still need to create our OrdersController. But the difference is that we now moved the responsiblity of building up object graphs to a single place in the application. We call this place the Composition Root.
Dependency Injection frameworks can help you making your Composition Root maintainable, but even without a DI framework, you build your object graph quite easy in MVC by implementing a custom ControllerFactory:
public class CompositionRoot : DefaultControllerFactory {
protected override IController GetControllerInstance(
RequestContext requestContext, Type controllerType) {
if (controllerType == typeof(OrdersController)) {
var connection = new Ajx.Dal.DapperConnection().getConnection();
return new OrdersController(
new OrdersService(
new OrdersRepository(
Disposable(connection))));
}
else if (...) {
// other controller here.
}
else {
return base.GetControllerInstance(requestContext, controllerType);
}
}
public static void CleanUpRequest() }
var items = (List<IDisposable>)HttpContext.Current.Items["resources"];
if (items != null) items.ForEach(item => item.Dispose());
}
private static T Disposable<T>(T instance)
where T : IDisposable {
var items = (List<IDisposable>)HttpContext.Current.Items["resources"];
if (items == null) {
HttpContext.Current.Items["resources"] =
items = new List<IDisposable>();
}
items.Add(instance);
return instance;
}
}
You can hook your custom controller factory in the Global asax of your MVC application like this:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
ControllerBuilder.Current.SetControllerFactory(
new CompositionRoot());
}
protected void Application_EndRequest(object sender, EventArgs e)
{
CompositionRoot.CleanUpRequest();
}
}
Of course, this all becomes much easier when you use a Dependency Injection framework. For instance, when you use Simple Injector (I'm the lead dev for Simple Injector), you can replace all of this with the following few lines of code:
using SimpleInjector;
using SimpleInjector.Integration.Web;
using SimpleInjector.Integration.Web.Mvc;
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
var container = new Container();
container.RegisterPerWebRequest<IDbConnection>(() =>
new Ajx.Dal.DapperConnection().getConnection());
container.Register<IOrdersRepository, OrdersRepository>();
container.Register<IOrdersService, OrdersService>();
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Verify();
DependencyResolver.SetResolver(
new SimpleInjectorDependencyResolver(container));
}
}
There are a few interesting things going on in the code above. First of all, the calls to Register tell Simple Injector that they need to return a certain implementation should be created when the given abstraction is requested. Next, Simple Injector allows registering types with the Web Request Lifestyle, which makes sure that the given instance is disposed when the web request ends (just as we did in the Application_EndRequest). By calling RegisterMvcControllers, Simple Injector will batch-register all Controllers for you. By supplying MVC with the SimpleInjectorDependencyResolver we allow MVC to route the creation of controllers to Simple Injector (just as we did with the controller factory).
Although this code might be a bit harder to understand at first, the use of a Dependency Injection container becomes really valuable when your application starts to grow. A DI container will help you keeping your Composition Root maintainable.
Well, if you're really paranoid about that you can use the finalizer (destructor) to automatically execute the Dispose when the object is being garbage collected. Check this link which explains basically all you need to know about IDisposable, skip to the Examples section if just want a quick sample how to do that. The finalizer(destructor) is the ~MyResource() method.
But any way, you should always encourage the consumers of your libraries to use correctly the Dispose. The automatic cleaning up, by means of garbage collector still presents flaws. You don't know when the garbage collector will do its job, so if you get lots of these classes instantiated and used, then forgotten, in a short time, you may still be in trouble.
I have a windows service, which contains a singleton which in turn uses some loggers, message queue listeners and so on. Those classes implements IDisposable. Should I implement IDisposable in singleton itself or do something else to ensure that after service stop/crashing everything will be okay with native resources?
The singleton is implemented like this:
public class Temp
{
private static readonly Lazy<Temp> instance = new Lazy<Temp>(() => new Temp());
private Temp()
{
// create IDisposable objects which use native resources
}
public static Temp Instance
{
get
{
return instance.Value;
}
}
}
I'd rather not implement IDisposable on singleton: IDisposable provokes developer to Dispose the (single) instance:
using(var temp = Temp.Instance) {
...
}
which leads to (possible) crash in some other part of the application (since the single Temp instance has been disposed):
Temp.Instance.SomeFucntion(); // <- possible fail, since Temp.Instanceis disposed
In some rare case if you have to release some resouces aquired, I'd use ProcessExit
event
public class Temp {
private static readonly Lazy<Temp> instance = new Lazy<Temp>(() => new Temp());
private void OnProcessExit(Object sender, EventArgs e) {
// Release native resource if required:
// some resources e.g. files will be closed automatically,
// but some e.g. transactions should be closed (commit/rollback) manually
try {
...
}
finally {
AppDomain.CurrentDomain.ProcessExit -= OnProcessExit;
}
}
private Temp() {
// create IDisposable objects which use native resources
// If you have to release some resouces on exit
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
}
public static Temp Instance {
get {
return instance.Value;
}
}
}
No; Singleton shouldn't implement IDisposable. What if someone disposes the instance prematurely when others are in need of that?
Also note that implementing IDisposable will not help you when your service is crashed/stopped. You'll have to dispose it manually! but you can't find right time to do it.
If a type will be returned from a factory that will sometimes need to be cleaned up when the caller is done with them, the type should implement IDisposable. If a particular factory returns a shared singleton object that doesn't actually need any resources, the object returned by the factory should have a Dispose method which silently does nothing. If the factory needs to provide access to a shared singleton resources (e.g. an immutable bitmap stored in a GDI object), it should return a wrapper which will notify the factory when it its Dispose method is called; the factory can then maintain a reference count of wrapper objects and clean up the resource once it knows that no more wrappers will be created and all existing wrappers have been disposed.
1)
public class DataProvider : IProvider , IDisposable{
private SqlConnection connection = null;
public DataProvider(string ConnectionString) {
this.connection = new SqlConnection(ConnectionString);
this.connection.Open();
}
public object GetUniqueData(SqlCommand CommandSql){}
public void ExecuteInsertDeleteUpdate(SqlCommand CommandSql){}
public void Dispose(){
if (this.connection != null) {
this.connection.Close();
this.connection.Dispose();
}
}
}
2)
public class ManageBrandDAL : IManageBrandDAL {
private IProvider provider = null;
[Inject]
public ManageBrandDAL (IProvider provider_){
this.provider = provider_;
}
public void RegisterBrand(string a_BrandName){
SqlCommand SQLCommand =
new SqlCommand("INSERT INTO Brand(name) VALUES(#pm_brandname)");
SqlParameter pm_brandname= new SqlParameter();
pm_brandname.ParameterName = "#pm_brandname";
pm_brandname.DbType = DbType.String;
pm_brandname.Value = a_BrandName;
SQLCommand.Parameters.Add(pm_brandname);
this.provider.ExecuteInsertDeleteUpdate(SQLCommand);
}
3)
public class ModuleInfra : Ninject.Modules.NinjectModule
{
public override void Load(){
Bind<IProvider>()
.To<ProvedorDados()
.InTransientScope()
.WithConstructorArgument("ConnectionString", Manage.ConnectionString);
}
}
How can I guarantee that the Ninject Container will call the method Dispose() in DataProvider class after ManageBrandDAL uses the DataProvider object?
Is the InTransientScope() the best lifecycle for this type of situation ? If not, what is more appropriate?
When you bind your DataProvider InTransientScope() it will not be disposed by Ninject, because actually transient scope is no scope at all. Ninject does not tracks objects that are bound in transient scope after it will create one for you.
Ninject disposes instances of objects implementing IDisposable as soon as the underlying scope object is collected by GC (but as as I said this does not work for objects bound to transient scope because there is no such scope object).
You should bind your DataProvider in scope, that is appropriate to your application. It could be:
InRequestScope() for web application (Ninject will dispose instances of objects implementing IDisposable after the end of the http request - don't forget to include OncePerWebRequest module)
InSingletonScope() - instance of object will be re-used for all subsequent requests during the whole lifecycle of application - from my point of view it is not an option for objects holding resources like SqlConnection
InThreadScope() - instance of object will be re-used within the same thread
InScope() - this could be used for creating custom scopes, so according to type of your application you can consider creating your own custom scope suitable to your needs.
There are also interesting extensions for Ninject that provides additional scope definitions: https://github.com/ninject/ninject.extensions.namedscope/wiki
Hints
You don't need to call both Close() and Dispose() on your SqlConnection. Dispose() is enough because it calls Close() internally.
I don't see the whole code, but do not forget to dispose the SqlCommand too.
If you let creating of instances of ManageBrandDAL on Ninject you don't need to use InjectAttribute on its constructor. It will unties you from using specific IOC provider.
Although a static class has only one instance and can't be instantiated, a class with a private constructor can't be instantiated (as the constructor can't be seen), so every time you call this class, this is the same one instance?
Factory classes always follow the last convention (instance class with private constructor). Why is this?
Thanks
There's nothing stopping the class with the private constructor from having a public static method which returns instances of the class:
public class NoPublicConstructor
{
private NoPublicConstructor()
{
}
public static NoPublicConstructor NewInstance()
{
return new NoPublicConstructor();
}
}
As you can see, the static method does not return the same one instance.
edit: One of the reasons factory classes do this is to be able to separate responsibility in future versions: while your code always calls the factory creation method, the author may move all the "guts" out of that class into a different one and your code won't need to know the difference. Calling that class' (public) constructor ties it to an extent to the original class implementation.
You can't* get an instance from outside the class, but you can from inside. A static method or an inner class can create and return an instance of the class with a private constructor. The static class cannot be instanced by anything.
class Foo
{
private Foo()
{
}
public class Bar
{
public Bar()
{
}
public Foo GetFoo()
{
return new Foo();
}
}
}
..
Foo.Bar fooBar = new Foo.Bar();
Foo foo = fooBar.GetFoo();
Edit: *I use the term "can't" loosely. Brian Rasmussen pointed out in the comments to the OP that another method to obtain an instance is through a call through System.Runtime.Serialization.FormatterServices, and this is external to the class itself.
Foo foo = (Foo)System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject(typeof(Foo));
Creating a class with private constructor is the common pattern for implementing a "Singleton" object.
The Singleton usually will instantiate an instance of itself, and only allow access to it through a static "Instance" property, which means there's only ever one instance of the class.
The advantage of using a Singleton over a purely static class is that you can utilize interfaces and different implementation classes within the singleton. Your "Singleton" might expose an interface for a set of methods, and you can choose which exact implementation class to instantiate under the covers. If you were using a purely static class, it would be hard to swap out a completely different implementation, without impacting other code.
The main downside of Singleton is that it's difficult to swap out the implementation class for testing, because it's controlled within the Singleton private methods, but there are ways to get around that.