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.
Related
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.
I'm working on a project that uses Unity Dependancy injection but the load performance is slowly getting worse. I am trying to adjust the code to utilise Lazy<T> (or Func<T>) so i'm trying to find a way to either register the classes with the container using Lazy<T> (or Func<T>) or have some sort of factory that could either adjust the registered types or the constructor but i am not able to seem to find a possible way to do this
At present i have numerous service classes like
public Service1(IClassLogic<GetReq, GetRes> getClass, IClassLogic<AddReq, AddRes> addClass, IClassLogic<UpdateReq, UpdateRes> updateClass, IClassLogic<DeleteReq, DeleteRes> deleteClass....){...}
then i have registrations similar to
container.RegisterType<IClassLogic<GetReq, GetRes>, GetClass>();
container.RegisterType<IClassLogic<AddReq, AddRes>, AddClass>();
container.RegisterType<IClassLogic<UpdateReq, UpdateRes>, UpdateClass>();
container.RegisterType<IClassLogic<DeleteReq, DeleteRes>, DeleteClass>();
...
Ideally i would like not to have to go an change all the signatures to
public Service1(Lazy<IClassLogic<GetReq, GetRes>> getClass, Lazy<IClassLogic<AddReq, AddRes>> addClass...
Any pointers would be greatly appreciated
Prevent using Func<T> and Lazy<T> as dependencies to prevent slow object graph initialization. These are leaky abstractions, because they leak implementation details into the consumer. The implementation detail here is that such service is costly to create.
The fact that it takes too much time to create a dependency is an indication that your injection constructors do too much, while they should be simple, fast and reliable.
Another obvious problem is the Single Responsibility Principle violation in your components. Having more than 5 dependencies in a constructor is a code smell and an indication of a Single Responsibility Principle violation. Some containers get slower when you need to resolve really big object graphs, but when you make your components small and focussed, this problem will quite likely go away, since the object graph to construct will be much smaller.
First off some tips concerning DI in general:
You're right, you do not want to change the signature of the constructor. You're IoC container (Unity in your case) should enable you to design the interfaces and consumers as you like. Otherwise it isn't a good container.
When struggling starting with DI (and containers) I would advise wiring it up yourself. This gives you great insight in how it works and provides flexibility. Mark Seemann has written a lot about this stuff.
Your service's dependencies seem awfully crowded. Can't you refactor to less dependencies by combining some (maybe by a Facade)?
Making interfaces specific (not generic) makes things a lot simpler. Generics sometimes cause more harm than good.
I've coded up a quick example which compiles (I haven't tested it). I've used a generic interface in line with your example but used some fake implementation and string types as generic params (which aren't used):
If this is an implementation of an interface:
public class ClassLogic : IClassLogic<string, string>
{
public void Do()
{
// do stuff
}
}
Then you could implement a provider which only creates the implementation when needed (via a given Func) like this:
public class ClassLogicProvider : IClassLogic<string, string>
{
private readonly Func<IClassLogic<string, string>> innerLogicFactory;
public ClassLogicProvider(Func<IClassLogic<string, string>> innerLogicFactory)
{
this.innerLogicFactory = innerLogicFactory;
}
public void Do()
{
var classLogic = this.innerLogicFactory();
classLogic.Do();
}
}
And wire it up like this:
var container = new UnityContainer();
Func<IClassLogic<string, string>> classLogicFunc = () =>
{
// Create implementation on demand
return new ClassLogic();
};
container.RegisterType<IClassLogic<string, string>>(
new InjectionFactory(c => {
return new ClassLogicProvider(classLogicFunc);
})
);
This should give you the desired Lazy creation when to implementation is needed.
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.
i'm working on a fork of the Divan CouchDB library, and ran into a need to set some configuration parameters on the httpwebrequest that's used behind the scenes. At first i started threading the parameters through all the layers of constructors and method calls involved, but then decided - why not pass in a configuration delegate?
so in a more generic scenario,
given :
class Foo {
private parm1, parm2, ... , parmN
public Foo(parm1, parm2, ... , parmN) {
this.parm1 = parm1;
this.parm2 = parm2;
...
this.parmN = parmN;
}
public Bar DoWork() {
var r = new externallyKnownResource();
r.parm1 = parm1;
r.parm2 = parm2;
...
r.parmN = parmN;
r.doStuff();
}
}
do:
class Foo {
private Action<externallyKnownResource> configurator;
public Foo(Action<externallyKnownResource> configurator) {
this.configurator = configurator;
}
public Bar DoWork() {
var r = new externallyKnownResource();
configurator(r);
r.doStuff();
}
}
the latter seems a lot cleaner to me, but it does expose to the outside world that class Foo uses externallyKnownResource
thoughts?
This can lead to cleaner looking code, but has a huge disadvantage.
If you use a delegate for your configuration, you lose a lot of control over how the objects get configured. The problem is that the delegate can do anything - you can't control what happens here. You're letting a third party run arbitrary code inside of your constructors, and trusting them to do the "right thing." This usually means you end up having to write a lot of code to make sure that everything was setup properly by the delegate, or you can wind up with very brittle, easy to break classes.
It becomes much more difficult to verify that the delegate properly sets up each requirement, especially as you go deeper into the tree. Usually, the verification code ends up much messier than the original code would have been, passing parameters through the hierarchy.
I may be missing something here, but it seems like a big disadvantage to create the externallyKnownResource object down in DoWork(). This precludes easy substitution of an alternate implementation.
Why not:
public Bar DoWork( IExternallyKnownResource r ) { ... }
IMO, you're best off accepting a configuration object as a single parameter to your Foo constructor, rather than a dozen (or so) separate parameters.
Edit:
there's no one-size-fits-all solution, no. but the question is fairly simple. i'm writing something that consumes an externally known entity (httpwebrequest) that's already self-validating and has a ton of potentially necessary parameters. my options, really, are to re-create almost all of the configuration parameters this has, and shuttle them in every time, or put the onus on the consumer to configure it as they see fit. – kolosy
The problem with your request is that in general it is poor class design to make the user of the class configure an external resource, even if it's a well-known or commonly used resource. It is better class design to have your class hide all of that from the user of your class. That means more work in your class, yes, passing configuration information to your external resource, but that's the point of having a separate class. Otherwise why not just have the caller of your class do all the work on your external resource? Why bother with a separate class in the first place?
Now, if this is an internal class doing some simple utility work for another class that you will always control, then you're fine. But don't expose this type of paradigm publicly.