Difference between Interface Injection and Method Injection [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have just started learning about Dependency Injection (DI) and its types in C#. I noticed that in almost all articles, the first two types of injection mechanisms mentioned are same, i.e., Constructor Injection and Property/Setter Injection.
But the third one is different in many articles - Some authors have mentioned "Interface-based Injection" as the third mechanism and some have mentioned "Method Injection". I may be wrong in my understanding of the same and they both could be the same thing, but just for my clarification, would like to know if there are any specific differences between the two of them?
Thanks in advance.
References: http://www.dotnettricks.com/learn/dependencyinjection/implementation-of-dependency-injection-pattern-in-csharp
http://www.c-sharpcorner.com/UploadFile/ff2f08/dependency-injection-pattern/

There are three basic DI patterns that describe how to inject a dependency:
Constructor Injection, is the act of statically defining the list of required Dependencies by specifying them as parameters to the class's constructor.
Property Injection (a.k.a. Setter Injection), statically defines an optional dependency using a property, when there already is a good Local Default.
Method Injection, allows supplying a consumer with a dependency by passing it in as method parameter, where this method is called outside the Composition Root
Martin Fowler however alo defined Interface Injection. This might seem like another form of DI, but it is in fact just a form of either Property Injection or Method Injection, where the property or method is part of the class's Abstraction. Interface Injection is to my knowledge not commonly used terminology.
Dependency Injection Principles, Practices, and Patterns describes that injection methods should always be placed on the Abstraction. When such injection method is implemented solely on the implementation, it means only the Composition Root can access them, but the book states:
Method Injection is unsuited to be used within the Composition Root. Within a Composition Root, Method Injection can be used to initialize a previously constructed class with its Dependencies. Doing so however leads to Temporal Coupling and is for that reason highly discouraged (§ 4.3.2).
Property Injection on the other hand, is typically solely used on the implementation rather than the Abstraction. That's because in the case of Property Injection it is the Composition Root that will set that dependency.
Interface Injection, as Fowler describes it, seems to be primarily used to initialize a component, but as stated above, that leads to Temporal Couping and should therefore be prevented. Either use Constructor Injection or use Method Injection without storing the dependency.
To get a better understanding of DI, you should read the freely available chapter 1 of that book.

Related

Is it good practice to use NSubstitute(or other testing frameworks that allow mocking) in the code(not in the tests)? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I faced with usage of NSubstitute inside business logic(outside of test classed):
var extension = Substitute.For<IExtension>();
I get used to utilization of NSubstitute inside test classes, when you need to mock some class(interface). But using NSubstitute outside of test classes confused me. Is it correct place for it? Is is correct to use NSubstitute like dependency injection container, that can create of instance of interface/class?
My concerns are that NSubstitute was designed to be used for tests. Performance inside tests is not very important thing, that is why it could be slow. Also, it relies on reflection, so it could not be very quick. But, is performance of NSubstitute poor, or is it ok?
Are there any other reasons, why NSubstitute or other mocking libraries should not be used outside of tests?
No, it is not generally good practice to use a mocking library in production code. (I'm going to use "generally" a lot here as I think any question on "good practice" will require a degree of generalisation. People may be able to come up with cases that work against this generalisation, but I think those cases will be the vast minority.)
Even without performance considerations, mocking libraries create test implementations for interfaces/classes. Test implementations generally support functions such as recording calls made and stubbing specific calls to return specific results. Generally when we have an interface or class for production code, it is to achieve some specific purpose, not the general purpose of recording calls and stubbing return values.
While it would be possible to provide a specific implementation for an interface using NSubstitute and to stub each call to execute production code logic, why not instead create a class with the required implementations instead?
This will generally have these advantages:
should be more succinct to implement (if not, consider switching to a better language! :D)
uses the native constructs of your programming language
should have better performance (removes levels of indirection required for mocking library)
For NSubstitute specifically there are some big reasons why you should never use it in production code. Because the library is designed for test code it uses some approaches that are unacceptable for production code:
It uses global state to support its syntax.
It abuses C#/VB syntax for the purpose of testing (can almost be considered a testing DSL). e.g. say sub.MyCall() returns an int. Stubbing a call like sub.MyCall().Returns(42) means we are calling int.Returns(42), which is now somehow going to influence a return value of a call outside of the int on which it is being called. This is quite different to how C#/VB generally works.
It requires virtual members for everything. This constraint is shared by many mocking libraries. For NSubstitute, you can get unpredictable results if you use it with non-virtual members. Unpredictability is not a nice thing to have for production code.
Tests are generally short-lived. NSubstitute (and probably other libraries) can make implementation decisions that rely on short-lived objects.
Tests show pass or failure for a particular case. This means if there is a problem in NSubstitute it can be immediately picked up while attempting to write and run a specific test. While a lot of effort goes into NSubstitute quality and reliability, the amount of work and scrutiny the C# compiler goes through is a completely different level. For production code, we want a very stable base to use as a foundation.
In summary: your programming language provides constructs designed and optimised for implementing logical interfaces. Your mocking library provides constructs designed and optimised for the much more limited task of providing test implementations of logical interfaces for use with testing code in isolation from its dependencies. Unless you have an ironclad reason as to why you would do the programming equivalent of digging a hole with a piece of paper instead of a shovel, I'd suggest using each tool for its intended purpose. :)

.Net Diference between Factory and Container? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I have never used a ioc-Container but from what I have read, the objects suffixed with "Container" seem to me a factory that reads from configuration/context, does its magic and returns an object of concrete type according to the read configuration/context.
What key aspects am I missing?
Using containers seems to add complexity (which is time consuming for development, refactoring and configuration), where to use and which are the key benefits?
Both IoC containers and factories build other objects, but that's where the similarities end.
A factory is an object which knows how to build other objects. It encapsulates extra logic, perhaps configuration time information etc. It can build several of a related type of objects, such as from a hierarchy of objects. But the number of objects it can build is part of the structure of the factory. So you might have a SqlConnectionFactory or a RequestHandlerFactory, which know what sort of SqlConnections or RequestHandlers to build, but if you want to build InputValidators you're going to need to make a new factory.
An IoC container is a tool used to help with the inversion of control pattern. But it's not strictly needed. IoC makes you be explicit in what dependencies your objects have, and makes you provide those dependencies when the object is created/initialized. When done right, this helps with separation of concerns, decoupling between components, unit testing etc. and generally makes the resulting code "better". But because manually wiring up object graphs is a hassle, a number of frameworks for doing this automatically, either from external configuration or from code annotations have appeared. These are called IoC containers. The way they initialize objects is much more generic than a factory. You can ask it to build any type of object, and as long as it knows something about those objects (the signature of the constructor, in the simplest case), it can build them.
It's more usual to see an IoC container use a factory, than the other way around. In much of the code I've seen, the need for factories for all but the most complex objects is greatly alleviated though.

Injection or creating instance with new() [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I'm a C# programmer and I'm thinking about dependency injection. I've read "Dependency injection in .NET" book and patterns and antipatterns of DI are quite clear for me. I use pattern injection in constructor most of the time. Are there any cases in wich it is preferrable to create instances directly rather than using a Dependency Injection framework?
Using Dependency Injection has the advantage of making code Testable, however abusing DI pattern makes code harder to understand. Take in example this framework (ouzel, I'm not affiliated in any way. I just liked the way it was designed) wich I started recently to follow, as you see most classes have dependencies injected, however there is still a single instance shared without constructor injection sharedEngine.
In that particular case I find the author did a good choice, that makes the code overall simpler to understand (simpler constructors, less members) and eventually more performant (you don't have a shared pointer stored in every instance of every class of the engine).
Still its code can be tested because you can replace that instance (global) with a mock (the worst point of globals is that initialization order and their dependencies are hard to track, however if you limit to few globals with no or few dependencies this is not a problem). As you see you are not always forced to inject everything from constructor (and I wrote a DI injection framework for C++).
The problem is that people think is always good injectin everything from constructor so you suddendly start seeing frameworks that allow to inject everything (like int or std::vector<float>) while in reality that's the worst idea ever (infact in my simple framework I allow just to inject classes) since code becomes harder to understand because you are mixing configuration values with logic configuration and you have to travel through more files to get a grasp of what code is doing.
So, constructor injection is very good, use it when it is proper, but it is not the Jack-of-all-trades like everything in programming you have to not abuse it. Best of all try to understand good examples of every programming practice/pattern and then roll your own recipe, programming is made of choices, and every choice have good and bad sides.
When is it Ok (and by "OK" I mean you will still be able to test the code, as it were not coupled to concrete instances) to call "new":
You need Polymorphis, most times it is easier to create the new class than configuring that using a DI framework
You need a object factory, usually the factory itself is injected, however the factory code call "new" explicitly
You are calling "new" in the main
The object you are creating with "new" has no dependencies, and thus using it inside a class does not make the class harder to test (in example you create standard .NET containers with new, doing otherwise results in much more confusion)
The object you are creating is a global instance wich do not rely on order of initialization and its dependencies are not visible otherelse (you can mock the instance as long as you access it through a interface).
The above list provide situations in wich even when using a DI framework (like Ninject) it is ok to call "new" without removing the possibility to test your code, even better, most times you use DI in the above cases you usually end up with more complex code.

Dependency injection using compile-time weaving? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
Improve this question
I just tried to learn about PostSharp and honestly I think it's amazing.
But one thing that it is difficult for me how a pure dependency injection (not service locator) cannot be done in PostSharp aspects, perhaps in my understanding as a result of compile time weaving.
Came from PHP background, Symfony has JMSAopBundle which still allows dependency to be injected to it's Interceptor.
Does .Net have some libraries with same capability?
Or am I missing something with PostSharp?
I don't think you're missing anything here and the limitation is indeed the result of using compile time weaving.
Although I think compile time weaving tools have its place in software development, I feel that they are often overused. Often I see them being used to patch flaws in the application design. In the applications I build I apply generic interfaces to certain architectural concepts. For instance, I define:
an ICommandHandler<TCommand> interface for services that implement a certain use case;
an IQueryHandler<TQuery, TResult> interface for services that execute a query;
an IRepository<TEntity> interface as abstraction over repositories;
an IValidator<TCommand> interface for components that execute message validation;
and so on, and so on.
This allows me to create a single generic decorator for such group of artifacts (for instance an TransactionCommandHandlerDecorator<TCommand> that allows running each use case in its own transaction). The use of decorators has many advantages, such as:
Those generic decorators are completely tool agnostic, since there is no reference to a code weaving tool or interception library. PostSharp aspects are completely dependent on PostSharp, and interceptors always take a dependency on an interception framework, such as Castle.DynamicProxy.
Because a decorator is just a normal component, dependencies can be injected into the constructor and they can play a normal role when you compose your object graphs using Dependency Injection.
The decorator code is very clean, since the lack of dependency with any third-party tool.
Because they're tool agnostic and allow dependency injection, decorators can be unit tested easily without having to revert to special tricks.
Application code that needs cross-cutting concerns to be applied can as well be tested easily in isolation, because decorators are not weaved in at compile time. When decorators are weaved in at compile time, you're always forced to do a integration style of testing of your application code, or need to revert to special build tricks to prevent them from being applied in your unit test project.
Decorators can be applied dynamically and conditionally at runtime, since there's no compile time code weaving going on.
Performance is identical (or even faster) than with code weaving, because there's no reflection going on during object construction.
There's no need to mark your components with attributes to note that some aspect must be applied. This keeps your application code free of any knowledge of such cross-cutting concern and makes it much easier to replace this.
A lot has been written about this kind of application design; here are a few articles I wrote myself:
Meanwhile... on the command side of my architecture
Meanwhile... on the query side of my architecture
Writing Highly Maintainable WCF Services
Chapter 10, Aspect-Oriented Programming by Design, of my book Dependency Injection Principles, Practices, Patterns contains a very detailed discussion on this type of design.
UPDATE
Decorators are great, but what I like about AOP is it's concept of
advice and join points. Is there a way to simulate the same capability
with decorator? I could only think of reflection right now.
A Join Point is a "well defined location within a class where a concern is going to be attached". When you apply AOP using decorators, you will be 'limited' to join points that are on the method boundaries. If however you adhere to the SRP, OCP and ISP, you will have very thin interfaces (usually with a single method). When doing that, you will notice that there is hardly ever a reason for having a join point at any other place in your classes.
An Advice is a "concern which will potentially change the input and/or output of the targeted method". When working with decorators and a message-based design (the thing I'm promoting here), your Advice needs to change the message (or replace the complete message with altered values) or change the output value. Things aren't that much different than with code weaving—if you apply an Advice, there must be something in common between all code the Advice is applied to.

in which cases should be used certain types of IoC frameworks [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I know that there are many IoC frameworks in .net ( They are: Ninject, Unity, Castle Windsor , Structure Map ) They also used to same goal - resolving dependencies. But i don't understand in which cases should be used certain framework! they are almost similar. Who can simply explain the main differences?
It depends on your needs. Some containers are very mature or have a big community. Others are feature rich or very fast. It all depends on what you need, but the problem is that you only know this when you already did one or two projects using DI and DI containers. And still, when you're architecture changes the requirements for your container will change.
So whatever container you pick, be prepared to change your container. This means, stick to the Dependency Injection pattern and prevent yourself from letting application code have a direct dependency on the container (a pattern which is called Service Locator).
Each and every one has a fatal flaw.
On a more serious note they surely do essentially the same thing, but differ in implementation details, conventions, performance, auxiliary features and suggested usecases.
I don't think that you should really sweat picking the IoC container. Stick to one you're used to and continue with your core functionality.
DI/IOC or whatever you want to call it is a means to an end - not the end in itself. Find one you like and that does everything you need and go with it (until you're told to use something else).
I rolled my own based on StructureMap and probably learned more doing that than actually using any of the others.

Categories