I'm a supporter of using Dependency Injection on your application, despite some people consider it add unnecessary complexity to the code.
In the past days I've wondered that, for some scenarios, there may be some waste when using DI.
Let me explain it with code examples:
Using DI
public class Class
{
private Service1 service1;
private Service2 service2;
public MyClass (Service1 service1, Service2 service2)
{
this.service1 = service1;
this.service2 = service2;
}
private int SampleMethod()
{
Console.WriteLine("doing something with service 1");
service1.DoSomething();
return 0;
}
private int SampleMethod2()
{
Console.WriteLine("doing something with service 2");
service2.DoSomethingElse();
return 1;
}
}
What if I rarely call SampleMethod2 and I will be injecting it every single time a Class instance is needed?
Wouldn't that be wasting resources?
I got this question a few days ago and I'm trying to figure out the response. Is it easier not using DI and let every method to create the instance they need when they get used in order to avoid this "waste"?
Is this a justified "waste" thanks to the decoupling that DI provides?
Yes it will be "wasted", but the nature of that waste depends on how its set up:
If Service2 is always created as a new instance; that's fairly expensive
If Service2 is in single instance mode, all its doing is fetching an existing instance (super cheap)
If Class is in single instance mode; its fetching that instance and not injecting anything new
Moreover, this would suggest a violation of SRP. Perhaps Class should be split into two objects, one that depends on Service1 and one that depends on Service 2 (or even both).
Regardless of the above, the "waste" is only important if it actually impacts your application, the benefits of DI vastly outweigh these kinds of problems.
Related
Way 1 new instance
public class LogicPacker : ILogicPacker
{
private IClassDI ClassDI { get; set; }
public LogicPacker (IClassDI ClassDI){
this.ClassDI = ClassDI;
}
private ICommentervice ICommentervice { get; set; }
public ICommentervice Commentervice
{
get { return ICommentervice ?? (ICommentervice = new Commentervice(ClassDI)); }
set { ICommentervice = value; }
}
}
Way 2 AddScoped
public void ConfigureServices(IServiceCollection services)
{
//IClassDI is absolutely add scope not change
services.AddScoped<IClassDI , ClassDI>();
...
services.AddScoped<ICommentservice, Commentservice>();
}
Below this is my service class
public class Commentservice : ICommentservice
{
private IClassDI ClassDI{ get; set; }
public Commentservice(IClassDI ClassDI)
{
this.ClassDI= ClassDI;
}
}
In my code i not sure about performance between use ioc AddScoped or new instance.
Way 1 i think it will be have trouble when i need to inject other to class Commentservice in future it will be make me confuse and annoying.
But Way 1 when i have more class in ILogicPacker i just inject ILogicPacker and need not to inject service anymore to other class is need to use service (if inject to much it will be new instance at constructor to much that i think)
Way 2 is use ioc add that to startup and don't be worry about number of di is need to inject to service.
If have something i think it wrong tell me and comment please.
This isn't really about performance, it's about managing lifetimes and scopes. While instantiating a class incurs some performance hit, it's usually too minuscule to even note, like micro or even nanoseconds. The reason to use DI is to scope dependencies and reuse dependencies.
Consider DbContext, for example. It handles things like change tracking and implements object caches, enabling things like relationship fix-up without having to issue additional queries. However, for those things to function properly, you need to use the same instance everywhere. If you create a new instance every time you use it, then the change tracking can get off, sometimes with disastrous effects, and at the very least, you lose out of all the various performance optimizations it offers. A DI container lets you share dependencies like this without having to think about it.
There's also the issue of handling object disposal, which a lot of people don't think about. If you new up a bunch of stuff in a class, you should also dispose of those things when no longer needed. This is handled via the IDisposable interface, which is deceptively hard to implement correctly. If you fail to dispose of the things you new up, you're essentially leaking memory. Sure, the GC will eventually clean up after you, but relying on the GC is just bad design. A DI container takes the thought out of this as well. It controls the lifetime of the objects it injects, and disposes of them when it truly makes sense to. Your classes are simply injected with the dependencies, so it's no longer the classes' concern as to when or if the resources are disposed. And, of course, reducing concerns is a fundamental paradigm of good design.
here is a sample of singleton design pattern code. i just new few scenario when people design singleton class.....please mention few scenario.
i often saw people develop logger with singleton design pattern approach but why it is required because we can develop a logger without singleton design pattern.
if anyone knows real reason please share with me. thanks
public sealed class Singleton
{
Singleton()
{
}
private static readonly object padlock = new object();
private static Singleton instance = null;
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}
It comes down to the needs of the application as to whether or not a singleton is needed. Generally you'd like to avoid using the pattern as there are usually instance-level ways of doing things like sharing data across threads, etc. though doing so may involve writing more complex code.
One example would be to cache database look-ups across processes. Any implementation is specific to the needs application, though it may not necessarily be required, i.e., as there usually other ways of achieving the same aim.
There is a better explanation of the whys on the software engineering site of SE here.
Singleton makes since when the object is expensive to construct, but in most application architectures today there isn't a lot of room for the singleton pattern as described in the Gang of Four book. The "classic" implementation of a singleton as you described makes use of static methods, which in turn become a major dependency magnet and make it more difficult to accomplish IoC. I can't think of a case today where I would use an object specifically coded as a singleton rather than pass an object that happens to be the only one constructed.
The way that I would today achieve the goal represented by the Singleton pattern would be to configure my IoC container to create only a single instance of that particular type when resolving dependencies.
I am new to Linq to sql. And my question is simple.
Is it a good idea to have DataContext as public static member in DAL to act as singleton?
It is not really good idea to keep DataContext as singleton, for small application, you might not see any consequences, but if your web application which has many users to access, it will lead to memory leak. Why?
DataContext basically implements Unit Of Work behind the scene which has internal cache inside to track changes of entities and avoid round trip to database in one business transaction. Keeping DataContext for long time as static, it means internal cache will be increasing for the time being and is not released properly.
DataContext should be kept in one business transaction and release as soon as possible. Best practice for web application is to keep DataContext as per request. You are also able to make use of IoC Container, most of IoC Container support this.
I have also experienced one thing while using shared datacontext in DAL. Suppose there are two users A and B. If User A starts and transaction then user B can commit changes made by user A which is a side effect of using static DataContext.
I generally try to group functionality together for a Data Access class and make that class IDisposable.
Then you Create your DataContext in your constructor and in your dispose method you run your .dispose() call on the DataContext.
So then when you need something from that class you can wrap it in a using statement, and make a bunch of calls all using the same DataContext.
It's pretty much the same effect as using a Static DataContext, but means you don't forget to close down the connection, and it seems a bit more OO than making things static.
public class MyDataAccessClass: IDisposable
{
private readonly DbDataContext _dbContext;
public MyDataAccessClass()
{
_dbContext = new DbDataContext ();
}
public void Dispose()
{
_dbContext.Dispose();
}
public List<CoolData> GetStuff()
{
var d = _dbContext.CallStuff();
return d;
}
}
Then in your class
using(var d = new MyDataAccessClass())
{
//Make lots of calls to different methods of d here and you'll reuse your DataContext
}
I recommend you to read about 'unit of work' pattern. I.e. http://stuartharris4.blogspot.com/2008/06/working-together-linq-to-sql.html
You most definitely should not have a static DataContext in a multi-threaded application such as ASP.NET. The MSDN documentation for DataContext states that:
Any instance members are not guaranteed to be thread safe.
Abstract
For the past few months I have been programming a light weight, C# based game engine with API abstraction and entity/component/scripting system. The whole idea of it is to ease the game development process in XNA, SlimDX and such, by providing architecture similar to that of the Unity engine.
Design challenges
As most game developers know, there are a lot of different services you need to access throughout your code. Many developers resort to using global static instances of e.g. a Render manager(or a composer), a Scene, Graphicsdevice(DX), Logger, Input state, Viewport, Window and so on. There are some alternative approaches to the global static instances/ singletons. One is to give each class an instance of the classes it needs access to, either through a constructor or constructor/property dependency injection(DI), another is to use a global service locator, like StructureMap's ObjectFactory where the service locator is usually configured as an IoC container.
Dependency Injection
I chose to go the DI way for many reasons. The most obvious one being testability, by programming against interfaces and have all the dependencies of every class provided to them through a constructor, those classes are easily tested since the test container can instantiate the required services, or the mocks of them, and feed into every class to be tested. Another reason for doing DI/IoC was, believe it or not, to increase the readability of the code. No more huge initialization process of instantiating all the different services and manually instantiating classes with references to the required services. Configuring the Kernel(NInject)/Registry(StructureMap) conveniently gives a single point of configuration for the engine/game, where service implementations are picked and configured.
My problems
I often feel like I am creating interfaces for interfaces sake
My productivity has gone down dramatically since all I do is worry about how to do things the DI-way, instead of the quick and simple global static way.
In some cases, e.g. when instantiating new Entities on runtime, one needs access to the IoC container / kernel to create the instance. This creates a dependency on the IoC container itself (ObjectFactory in SM, an instance of the kernel in Ninject), which really goes against the reason for using one in the first place. How can this be resolved? Abstract factories come to mind, but that just further complicates the code.
Depending on service requirements, some classes' constructors can get very large, which will make the class completely useless in other contexts where and if an IoC is not used.
Basically doing DI/IoC dramatically slows down my productivity and in some cases further complicates the code and architecture. Therefore I am uncertain of whether it is a path I should follow, or just give up and do things the old fashioned way. I am not looking for a single answer saying what I should or shouldn't do but a discussion on if using DI is worth it in the long run as opposed to using the global static/singleton way, possible pros and cons I have overlooked and possible solutions to my problems listed above, when dealing with DI.
Should you go back to the old-fashioned way?
My answer in short is no. DI has numerous benefits for all the reasons you mentioned.
I often feel like I am creating interfaces for interfaces sake
If you are doing this you might be violating the
Reused Abstractions Principle (RAP)
Depending on service requirements, some classes' constructors can get
very large, which will make the class completely useless in other
contexts where and if an IoC is not used.
If your classes constructors are too large and complex, this is the best way to show you that you are violating a very important other principle:
Single Reponsibility Principle. In this case it is time to extract and refactor your code into different classes, the number of dependencies suggested is around 4.
In order to do DI you don't have to have an interface, DI is just the way you get your dependencies into your object. Creating interfaces might be a needed way to be able to substitute a dependency for testing purposes.
Unless the object of the dependency is:
Easy to isolate
Doesn't talk to external subsystems (file system
etc)
You can create your dependency as an Abstract class, or any class where the methods you'd like to substitute are virtual. However interfaces do create the best de-coupled way of an dependency.
In some cases, e.g. when instantiating new Entities on runtime, one
needs access to the IoC container / kernel to create the instance.
This creates a dependency on the IoC container itself (ObjectFactory
in SM, an instance of the kernel in Ninject), which really goes
against the reason for using one in the first place. How can this be
resolved? Abstract factories come to mind, but that just further
complicates the code.
As far as a dependency to the IOC container, you should never have a dependency to it in your client classes.
And they don't have to.
In order to first use dependency injection properly is to understand the concept of the Composition Root. This is the only place where your container should be referenced. At this point your entire object graph is constructed. Once you understand this you will realize you never need the container in your clients. As each client just gets its dependency injected.
There are also MANY other creational patterns you can follow to make construction easier:
Say you want to construct an object with many dependencies like this:
new SomeBusinessObject(
new SomethingChangedNotificationService(new EmailErrorHandler()),
new EmailErrorHandler(),
new MyDao(new EmailErrorHandler()));
You can create a concrete factory that knows how to construct this:
public static class SomeBusinessObjectFactory
{
public static SomeBusinessObject Create()
{
return new SomeBusinessObject(
new SomethingChangedNotificationService(new EmailErrorHandler()),
new EmailErrorHandler(),
new MyDao(new EmailErrorHandler()));
}
}
And then use it like this:
SomeBusinessObject bo = SomeBusinessObjectFactory.Create();
You can also use poor mans di and create a constructor that takes no arguments at all:
public SomeBusinessObject()
{
var errorHandler = new EmailErrorHandler();
var dao = new MyDao(errorHandler);
var notificationService = new SomethingChangedNotificationService(errorHandler);
Initialize(notificationService, errorHandler, dao);
}
protected void Initialize(
INotificationService notifcationService,
IErrorHandler errorHandler,
MyDao dao)
{
this._NotificationService = notifcationService;
this._ErrorHandler = errorHandler;
this._Dao = dao;
}
Then it just seems like it used to work:
SomeBusinessObject bo = new SomeBusinessObject();
Using Poor Man's DI is considered bad when your default implementations are in external third party libraries, but less bad when you have a good default implementation.
Then obviously there are all the DI containers, Object builders and other patterns.
So all you need is to think of a good creational pattern for your object. Your object itself should not care how to create the dependencies, in fact it makes them MORE complicated and causes them to mix 2 kinds of logic. So I don't beleive using DI should have loss of productivity.
There are some special cases where your object cannot just get a single instance injected to it. Where the lifetime is generally shorter and on-the-fly instances are required. In this case you should inject the Factory into the object as a dependency:
public interface IDataAccessFactory
{
TDao Create<TDao>();
}
As you can notice this version is generic because it can make use of an IoC container to create various types (Take note though the IoC container is still not visible to my client).
public class ConcreteDataAccessFactory : IDataAccessFactory
{
private readonly IocContainer _Container;
public ConcreteDataAccessFactory(IocContainer container)
{
this._Container = container;
}
public TDao Create<TDao>()
{
return (TDao)Activator.CreateInstance(typeof(TDao),
this._Container.Resolve<Dependency1>(),
this._Container.Resolve<Dependency2>())
}
}
Notice I used activator even though I had an Ioc container, this is important to note that the factory needs to construct a new instance of object and not just assume the container will provide a new instance as the object may be registered with different lifetimes (Singleton, ThreadLocal, etc). However depending on which container you are using some can generate these factories for you. However if you are certain the object is registered with Transient lifetime, you can simply resolve it.
EDIT: Adding class with Abstract Factory dependency:
public class SomeOtherBusinessObject
{
private IDataAccessFactory _DataAccessFactory;
public SomeOtherBusinessObject(
IDataAccessFactory dataAccessFactory,
INotificationService notifcationService,
IErrorHandler errorHandler)
{
this._DataAccessFactory = dataAccessFactory;
}
public void DoSomething()
{
for (int i = 0; i < 10; i++)
{
using (var dao = this._DataAccessFactory.Create<MyDao>())
{
// work with dao
// Console.WriteLine(
// "Working with dao: " + dao.GetHashCode().ToString());
}
}
}
}
Basically doing DI/IoC dramatically slows down my productivity and in
some cases further complicates the code and architecture
Mark Seeman wrote an awesome blog on the subject, and answered the question:
My first reaction to that sort of question is: you say loosely coupled code is harder to understand. Harder than what?
Loose Coupling and the Big Picture
EDIT: Finally I'd like to point out that not every object and dependency needs or should be dependency injected, first consider if what you are using is actually considered a dependency:
What are dependencies?
Application Configuration
System Resources (Clock)
Third Party Libraries
Database
WCF/Network Services
External Systems (File/Email)
Any of the above objects or collaborators can be out of your control and cause side effects and difference in behavior and make it hard to test. These are the times to consider an Abstraction (Class/Interface) and use DI.
What are not dependencies, doesn't really need DI?
List<T>
MemoryStream
Strings/Primitives
Leaf Objects/Dto's
Objects such as the above can simply be instantiated where needed using the new keyword. I would not suggest using DI for such simple objects unless there are specific reasons. Consider the question if the object is under your full control and doesn't cause any additional object graphs or side effects in behavior (at least anything that you want to change/control the behavior of or test). In this case simply new them up.
I have posted a lot of links to Mark Seeman's posts, but I really recommend you read his book and blog posts.
I had a habit to pass logger to constructor, like:
public class OrderService : IOrderService {
public OrderService(ILogger logger) {
}
}
But that is quite annoying, so I've used it a property this for some time:
private ILogger logger = NullLogger.Instance;
public ILogger Logger
{
get { return logger; }
set { logger = value; }
}
This is getting annoying too - it is not dry, I need to repeat this in every class. I could use base class, but then again - I'm using Form class, so would need FormBase, etc.
So I think, what would be downside of having singleton with ILogger exposed, so veryone would know where to get logger:
Infrastructure.Logger.Info("blabla");
UPDATE: As Merlyn correctly noticed, I've should mention, that in first and second examples I am using DI.
I put a logger instance in my dependency injection container, which then injects the logger into the classes which need one.
This is getting annoying too - it is not DRY
That's true. But there is only so much you can do for a cross-cutting concern that pervades every type you have. You have to use the logger everywhere, so you must have the property on those types.
So lets see what we can do about it.
Singleton
Singletons are terrible <flame-suit-on>.
I recommend sticking with property injection as you've done with your second example. This is the best factoring you can do without resorting to magic. It is better to have an explicit dependency than to hide it via a singleton.
But if singletons save you significant time, including all refactoring you will ever have to do (crystal ball time!), I suppose you might be able to live with them. If ever there were a use for a Singleton, this might be it. Keep in mind the cost if you ever want to change your mind will be about as high as it gets.
If you do this, check out other people's answers using the Registry pattern (see the description), and those registering a (resetable) singleton factory rather than a singleton logger instance.
There are other alternatives that might work just as well without as much compromise, so you should check them out first.
Visual Studio code snippets
You could use Visual Studio code snippets to speed up the entrance of that repetitive code. You will be able to type something like loggertab, and the code will magically appear for you.
Using AOP to DRY off
You could eliminate a little bit of that property injection code by using an Aspect Oriented Programming (AOP) framework like PostSharp to auto-generate some of it.
It might look something like this when you're done:
[InjectedLogger]
public ILogger Logger { get; set; }
You could also use their method tracing sample code to automatically trace method entrance and exit code, which might eliminate the need to add some of the logger properties all together. You could apply the attribute at a class level, or namespace wide:
[Trace]
public class MyClass
{
// ...
}
// or
#if DEBUG
[assembly: Trace( AttributeTargetTypes = "MyNamespace.*",
AttributeTargetTypeAttributes = MulticastAttributes.Public,
AttributeTargetMemberAttributes = MulticastAttributes.Public )]
#endif
Good question. I believe in most projects logger is a singleton.
Some ideas just come to my mind:
Use ServiceLocator (or an other Dependency Injection container if you already using any) which allows you to share logger across the services/classes, in this way you can instantiate logger or even multiple different loggers and share via ServiceLocator which is obviously would be a singleton, some kind of Inversion of Control. This approach gives you much flexibility over a logger instantiation and initialization process.
If you need logger almost everywhere - implement extension methods for Object type so each class would be able to call logger's methods like LogInfo(), LogDebug(), LogError()
A singleton is a good idea. An even better idea is to use the Registry pattern, which gives a bit more control over instantiation. In my opinion the singleton pattern is too close to global variables. With a registry handling object creation or reuse there is room for future changes to instantiation rules.
The Registry itself can be a static class to give simple syntax to access the log:
Registry.Logger.Info("blabla");
A plain singleton is not a good idea. It makes it hard to replace the logger. I tend to use filters for my loggers (some "noisy" classes may only log warnings/errors).
I use singleton pattern combined with the proxy pattern for the logger factory:
public class LogFactory
{
private static LogFactory _instance;
public static void Assign(LogFactory instance)
{
_instance = instance;
}
public static LogFactory Instance
{
get { _instance ?? (_instance = new LogFactory()); }
}
public virtual ILogger GetLogger<T>()
{
return new SystemDebugLogger();
}
}
This allows me to create a FilteringLogFactory or just a SimpleFileLogFactory without changing any code (and therefore complying to Open/Closed principle).
Sample extension
public class FilteredLogFactory : LogFactory
{
public override ILogger GetLogger<T>()
{
if (typeof(ITextParser).IsAssignableFrom(typeof(T)))
return new FilteredLogger(typeof(T));
return new FileLogger(#"C:\Logs\MyApp.log");
}
}
And to use the new factory
// and to use the new log factory (somewhere early in the application):
LogFactory.Assign(new FilteredLogFactory());
In your class that should log:
public class MyUserService : IUserService
{
ILogger _logger = LogFactory.Instance.GetLogger<MyUserService>();
public void SomeMethod()
{
_logger.Debug("Welcome world!");
}
}
There is a book Dependency Injection in .NET. Based on what you need you should use interception.
In this book there is a diagram helping to decide whether to use Constructor injection, property injection, method injection, Ambient Context, Interception.
That's how one reasons using this diagram:
Do you have dependency or need it? - Need it
Is it cross-cutting concern? - Yes
Do you need an answer from it? - No
Use Interception
Another solution I personally find the easiest is to use a static Logger class. You can call it from any class method without having to change the class, e.g. add property injection etc. Its pretty simple and easy to use.
Logger::initialize ("filename.log", Logger::LEVEL_ERROR); // only need to be called once in your application
Logger::log ("my error message", Logger::LEVEL_ERROR); // to be used in every method where needed
If you want to look at a good solution for logging I suggest you look at google app engine with python where logging is as simple as import logging and then you can just logging.debug("my message") or logging.info("my message") which really keeps it as simple as it should.
Java didn't have a good solution for logging ie log4j should be avoided since it practically forces you to use singletons which as answered here is "terrible" and I've had horrible experience with trying to make logging output the same logging statement only once when I suspect that the reason for double logging was that I have one Singleton of the logging object in two classloaders in the same virtual machine(!)
I beg your pardon for not being so specific to C# but from what I've seen the solutions with C# look similar Java where we had log4j and we also should make it a singleton.
That's why I really liked the solution with GAE / python, it's as simple as it can be and you don't have to worry about classloaders, getting double logging statement or any design patterna at all for that matter.
I hope some of this information can be relevant to you and I hope that you want to take a look at I logging solution I recommend instead of that I bully down on how much problem Singleton get suspected due to the impossibility of having a real singleton when it must be instanciating in several classloaders.