ways of using ninject properly - asp.net-mvc

One of the definition of ninject in internet is;
"Somewhere in the middle of your application, you're creating a class
inside another class. That means you're creating a dependency.
Dependency Injection is about passing in those dependencies, usually
through the constructor, instead of embedding them."
what i want to learn is, where ever we see a creation of a class inside another class should we use ninject or just we should use in some part of program that we want/need to apply loosely coupling for design purposes because maybe we would like to use different approaches in the future?
Sorry if this is a silly question.

It's a perfectly valid question, and there are no absolute right or wrong answers. Ninject and other IoC frameworks are designed to de-couple dependencies.
So the moment you do this:
public class MyClass1
{
public MyClass1()
{
MyClass2 mc2 = new MyClass2();
}
}
You can categorically say that MyClass1 has a dependency in MyClass2.
For me, my rule is this: do I need to unit test MyClass1, or is it likely I'll need to unit test MyClass1?
If I don't need to unit test it, then I don't find much value in decoupling the two classes.
However, if I do need to unit test MyClass1, then injecting in MyClass2 gives you much better control over your unit tests (and allows you to test MyClass1 in isolation).
You do need to evaluate each case separately though. In the above example, if I need to unit test MyClass1, and MyClass2 is just a basic string formatting class, then I probably wouldn't decouple it. However, if MyClass2 was an email sending class then I would de-couple it. I don't want my unit tests actually sending emails, so I would feed in a fake for my tests instead.
So I don't believe there are any solid rules, but hopefully the above gives you a better idea of when you might decouple, and when you might not decouple.

Related

what is the main purpose technically speaking about the abstraction in programming using DI, Interfaces, and Abstract Classes? [closed]

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 months ago.
Improve this question
I viewed a couple of answers online regarding Abstractions, Abstract Classes, Interface's, DI, and Loose coupling. But none of these answers are answering my question. I grouped these topics because they are related to achieving abstractions. Got a good understanding of the mentioned topics, but yet not fully understand them in detail and how they related to each other.
Generally speaking, interfaces are used to make classes loosely coupled. Thus define a set of functions and fields to be implemented. The idea of making Loosely Coupled classes is that will need to remove dependency over several classes.
For instance, if we make a change to one of these classes then we do not need to change other places making code maintainable. The only good example I can think of to use loosely coupling is through DI. So when we say interfaces make classes loosely coupled do we mean by passing an interface as a dependency?
"Please continue reading will further clarify".
A question here is if we are going to use DI and pass interfaces as dependencies then why not pass a class as a dependency instead? maybe I will need further clarification about Interfaces before answering the previous question. I will further explain.
The main idea of interfaces is to establish contact with classes that going to implement the interface meaning we are going to need to define functions and fields to enforce to implement them. but still, the idea of interfaces as a contract is not yet clear because if we enforce a developer to implement an interface called a server that has methods to turn on and off the server but the developer forgot to turn off the server programmatically then what is the point of this contract?
Further, my understanding is that this all falls under the concept of abstraction which means we do not need to worry about details but an abstraction. Does that not mean when building an application we first need to create classes/structures without code such as using UML?
Further, why would we use an abstract class over interfaces where an abstract class has similarities to an interface such as defining a function but without a body?
Coming back to Interfaces and DI we can inject interfaces as a dependency but why? Can we not inject a class it self? is it not easier to use classes as a dependency? where we can access all functions or this is not the idea of interface Can sombody help with this. I only understand one use case on why we should use DI. Example:
//Class1
//Class1 Con
Public Class1 Con(){
Class2 class2 = new Class2(1,1,1)
}
The above example is not maintainable because if we add a new parameter to Class2 then we need to modify it elsewhere. but if we use DI Injection then we won't are there any other reasons.
Also, DI can be useful to create one instance and use that instance across the whole application. Does that save some memory by not creating multiple instances? or saving time connecting to DI?
The question should we use abstractions at the very early coding stage where we create classes without code?
Further, do we use interfaces to make the developer aware that they need to implement a certain set of functions? But why?
Do I predict that we need to use an interface by creating UML diagrams to see if there would be different classes to use an interface with similar functionalities
"Can we not just create a superclass and override methods"
Can somebody explain when to use superclass and override methods over interfaces and provide an implementation?
Also, when to pass an interface as a dependency? And when to pass a class as a dependency? One advantage I can think of when using interfaces is polymorphism where we can make an interface of any implemented types and then access the interface type function; polymorphism. Example:
Class1 class = new Interface1();
Can this be possible?
Bottom line is we would like always to make our class's loosely coupled. Meaning that decouple class's to achieve maintainable. Thus, loosely coupled classes provider's late binding, extensibility, maintainability and easy testing. May refer to reference 1. We use interface's to make class's loosely coupled as well. but before answering how. we need to understand interface's why we use them and how they are different to abstract class's. Interface's are mainly used as contract meaning that when we create multiple class's sharing same behaviour but with different implementation then we use interface's. Thus, its a set of infrastructure to tell developer's what method's to implement. interface's only includes functions, fields signature with no implementation.
How we use DI to achieve loosely coupled class's is by injecting dependencies. suppose the following class's implements interface called Database:
public interface Database
{
void Save();
}
class SqlServer : Database
{
public void Save()
{
Console.WriteLine("Saving...");
}
}
class Oracle : Database
{
public void Save()
{
Console.WriteLine("Saving...");
}
}
Then we can easily inject dependencies as follows:
class Library
{
//private Database _SqlServer;
private Database _Oracle;
public Student(IDAL _SqlServer)
{
this._SqlServer = _SqlServer;
}
public void SaveBoo()
{
_SqlServer.Save();
}
}
Using the above approach we are injecting dependencies meaning that class's are now not fully tightly coupled. if any change made to _SqlServer we do not have to worry. To achieve full decoupled class's then use DI container Refer to reference 1.
The difference between abstract class's and interface's is that we use interface to define a contract where we use abstract if we want partial implementation. In Abstract class's you can define some method's implementation while leaving other as abstract.
You may create UML class diagrams to represent class's relationship without the need to worry about the coding side yet
As I am replying to my own question I would think it’s good to create classes and relationship I will call it classes structure then do all code later in case UML Class diagram is not going to be used. I guess this will fall under the technique/concept that is called abstraction where we do not yet worry about the details yet. So we can have an image about how is the application is structured without using UML’s.
Hope make sense
References:
(https://findnerd.com/account/#url=/list/view/Dependency-Injection-in--Net/24098/)

Why is mocking with DI better than mocking objects in objective-c?

this blog article says that:
While there are sometimes sensible ways to mock out objects without DI
(typically by mocking out class methods, as seen in the OCMock example
above), it’s often flat out not possible. Even when it is possible,
the complexity of the test setup might outweigh the benefits. If
you’re using dependency injection consistently, you’ll find writing
tests using stubs and mocks will be much easier.
but it doesn't explain why. What are possible scenarios where DI (injecting an id object conforming to protocol) will serve better for mocking in Objective-C, than simple OCMockito:
[given([mockArray objectAtIndex:0]) willReturn:#"first"];
[verifyCount(mockArray, times(1)) objectAtIndex:];
?
I've noticed that it is easier to create a separate class for test target when the original class do some async stuff.
Let assume you write a test for UIViewController which has a LoginSystem dependency which uses AFNetworking to do a request to the API. LoginSystem takes a block argument as a callback. (UIViewController->LoginSystem->AFNetworking).
If you make a mock of LoginSystem probably you will end with problems how to fire a callback block to test your UIViewController behaviour on success/failure. When I tried that I ended with MKTArgumentCaptor to retrieve a block argument and then I had to invoke it inside a test file.
On the other hand, if you create a separate class for LoginSystem (let call it LoginSystemStub which extends from LoginSystem) you are able to "mock" a behaviour in 3 lines of code and outside the test file. We should also keep our test file clean and readable.
Another case is that verify() doesn't work with checking asynchronous behaviour. It is much more easier to call expect(smth2).will.equal(smth)
EDIT:
Pointers to NSError (NSError**) also don't work well with verify() and it's better to create a stub :D
Imagine you are trying to test a more complex behavior of an object interacting with one of its child objects. To make certain that the parent object is operating correctly, you have to mock all the methods of the child object and even potentially track its changing state.
But if you do that, you just wrote an entirely new object in a confusing and convoluted way. It would have been simpler to write an entirely new object and tell the parent to use that.
With DI you inject your model at runtime, it's not bound in your classes but only in the configuration.
When you want to mock you just create a mock model and inject that instead of your real data. Besides the model, you changed your implementation in a single line.
See here for a hands on example or here for the idea behind it.
Disclaimer: Of course you can mock other stuff than the model, but that's probably the most common use-case.
The answer is: It's not better. It's only better if you need some super custom behavior.
The best thing about it is that you don't have to create an interface/protocol for every class you inject and you can limit to DI the modules you really need to inject making your code cleaner and more YAGNI.
It applies to any dynamic language, or language with reflection. Creating so much clutter just for the sake of Unit-Tests struck me as a bad idea.

Laravel 4: Facade vs DI (when to use)

My understanding is that a facade is used as an alternative to dependency injection. Please correct if I'm mistaken. What is not clear is when one should use one or the other.
What are the advantages/disadvantages of each approach? How should I determine when to use one or the other?
Lastly, why not use both? I can create a facade that references an interface. It seems Sentry 2 is written this way. Is there a best practice?
FACADES
Facades are not an alternative to dependency injection.
Laravel Facade is an implementation of the Service Locator Pattern, creating a clean and beautiful way of accessing objects:
MyClass::doSomething();
This is the PHP syntax for a static methods, but Laravel changes the game and make them non-static behind the scenes, giving you a beautiful, enjoyable and testable way of writing your applications.
DEPENDENCY INJECTION
Dependency Injection is, basically, a way of passing parameters to your constructors and methods while automatically instatiating them.
class MyClass {
private $property;
public function __construct(MyOtherClass $property)
{
/// Here you can use the magic of Dependency Injection
$this->property = $property
/// $property already is an object of MyOtherClass
}
}
A better construction of it would be using Interfaces on your Dependency Injected constructors:
class MyClass {
private $property;
public function __construct(MyInterface $property)
{
/// Here you can use the magic of Dependency Injection
$this->property = $property
/// $property will receive an object of a concrete class that implements MyInterface
/// This class should be defined in Laravel elsewhere, but this is a way of also make
/// your application easy to maintain, because you can swap implementations of your interfaces
/// easily
}
}
But note that in Laravel you can inject classes and interfaces the same way. To inject interfaces you just have to tell it wich one will be this way:
App::bind('MyInterface', 'MyOtherClass');
This will tell Laravel that every time one of your methods needs an instance of MyInterface it should give it one of MyOtherClass.
What happens here is that this constuctor has a "dependency": MyOtherClass, which will be automatically injected by Laravel using the IoC container. So, when you create an instance of MyClass, Laravel automatically will create an instance of MyOtherClass and put it in the variable $class.
Dependency Injection is just an odd jargon developers created to do something as simple as "automatic generation of parameters".
WHEN TO USE ONE OR THE OTHER?
As you can see, they are completely different things, so you won't ever need to decide between them, but you will have to decide where go to with one or the other in different parts of your application.
Use Facades to ease the way you write your code. For example: it's a good practice to create packages for your application modules, so, to create Facades for those packages is also a way to make them seem like a Laravel public class and accessing them using the static syntax.
Use Dependency Injection every time your class needs to use data or processing from another class. It will make your code testable, because you will be able to "inject" a mock of those dependencies into your class and you will be also exercising the single responsibility principle (take a look at the SOLID principles).
Facades, as noted, are intended to simplify a potentially complicated interface.
Facades are still testable
Laravel's implementation goes a step further and allows you to define the base-class that the Facade "points" to.
This gives a developer the ability to "mock" a Facade - by switching the base-class out with a mock object.
In that sense, you can use them and still have testable code. This is where some confusion lies within the PHP community.
DI is often cited as making your code testable - they make mocking class dependencies easy. (Sidenote: Interfaces and DI have other important reasons for existing!)
Facades, on the other hand, are often cited as making testing harder because you can't "simply inject a mock object" into whatever code you're testing. However, as noted, you can in fact "mock" them.
Facade vs DI
This is where people get confused regarding whether Facades are an alternative to DI or not.
In a sense, they both add a dependency to your class - You can either use DI to add a dependency or you can use a Facade directly - FacadeName::method($param);. (Hopefully you are not instantiating any class directly within another :D ).
This does not make Facades an alternative to DI, but instead, within Laravel, does create a situation where you may decide to add class dependencies one of 2 ways - either using DI or by using a Facade. (You can, of course, use other ways. These "2 ways" are just the most-often used "testable way").
Laravel's Facades are an implementation of the Service Locator pattern, not the Facade pattern.
In my opinion you should avoid service locator within your domain, opting to only use it in your service and web transport layers.
http://martinfowler.com/articles/injection.html#UsingAServiceLocator
I think that in terms of laravel Facades help you keep you code simple and still testable since you can mock facades however might be a bit harder to tell a controllers dependencies if you use facades since they are probably all over the place in your code.
With dependency injection you need to write a bit more code since you need to deal with creating interfaces and services to handle the depenancies however Its a lot more clear later on what a controller depends on since these are clearly mentioned in the controller constructor.
I guess it's a matter of deciding which method you prefer using

Repository Pattern in asp.net mvc with linq to sql

I have been reading though the code of the NerdDinner app and specifically the Repository Pattern...
I have one simple question though, regarding this block
public DinnersController()
: this(new DinnerRepository()) {
}
public DinnersController(IDinnerRepository repository) {
dinnerRepository = repository;
}
What if each Dinner also had, say, a Category... my question is
Would you also initialize the category Repository in the constructor of the class??
Im sure it would work but Im not sure if the correct way would be to initialize the repository inside the method that is going to use that repository or just in the constructor of the class??
I would appreciate some insight on this issue
Thanks.
What you're looking at here is actually not so much to do with the repository pattern, per se, and more to do with "dependency injection," where the outside things on which this class depends are "injected" from without, rather rather than instantiated within (by calling new Repository(), for example).
This specific example shows "constructor injection," where the dependencies are injected when the object is created. This is handy because you can always know that the object is in a particular state (that it has a repository implementation). You could just as easily use property injection, where you provide a public setter for assigning the repository or other dependency. This forfeits the stated advantage of constructor injection, and is somewhat less clear when examining the code, but an inversion-of-control container can handle the work of instantiating objects and injecting dependencies in the constructor and/or properties.
This fosters proper encapsulation and improves testability substantially.
The fact that you aren't instantiating collaborators within the class is what improves testability (you can isolate the behaviour of a class by injecting stub or mock instances when testing).
The key word here when it comes to the repository pattern is encapsulation. The repository pattern takes all that data access stuff and hides it from the classes consuming the repository. Even though an ORM might be hiding all the actual CRUD work, you're still bound to the ORM implementation. The repository can act as a facade or adapter -- offering an abstract interface for accessing objects.
So, when you take these concepts together, you have a controller class that does not handle data access itself and does not instantiate a repository to handle it. Rather the controller accepts an injected repository, and knows only the interface. What is the benefit? That you can change your data access entirely and never ever touch the controller.
Getting further to your question, the repository is a dependency, and it is being provided in the constructor for the reasons outlined above. If you have a further dependency on a CategoryRepository, then yes, by all means inject that in the constructor as well.
Alternatively, you can provide factory classes as dependencies -- again classes that implement some factory interface, but instead of the dependency itself, this is a class that knows how to create the dependency. Maybe you want a different IDinnerRepository for different situations. The factory could accept a parameter and return an implementation according to some logic, and since it will always be an IDinnerRepository, the controller needs be none the wiser about what that repository is actually doing.
To keep your code decoupled and your controllers easily testable you need to stick with dependency injection so either:
public DinnersController()
: this(new DinnerRepository(), new CategoryRepository()) {
}
or the less elegant
public DinnersController()
: this(new DinnerRepository(new CategoryRepository())) {
}
I would have my dinner categories in my dinner repository personally. But if they had to be seperate the id put them both in the ctor.
You'd want to pass it in to the constructor. That said, I probably wouldn't create any concrete class like it's being done there.
I'm not familiar with the NerdDinner app, but I think the preferred approach is to define an IDinnerRepository (and ICategoryRepository). If you code against interfaces and wanted to switch to say, an xml file, MySQL database or a web service you would not need to change your controller code.
Pushing this out just a little further, you can look at IoC containers like ninject. The gist of it is is that you map your IDinnerRepository to a concrete implementation application wide. Then whenever a controller is created, the concrete repository (or any other dependency you might need) is provided for you even though you're coding against an interface.
It depends on whether you will be testing your Controllers (, which you should be doing). Passing the repositories in by the constructor, and having them automatically injected by your IOC container, is combining convenience with straightforward testing. I would suggest putting all needed repositories in the constructor.
If you seem to have a lot of different repositories in your constructors, it might be a sign that your controller is trying to do too many unrelated things. Might; sometimes using multiple repositories is legitimate.
Edit in response to comment:
A lot of repositories in one controller constructor might be considered a bad code smell, but a bad smell is not something wrong; it is something to look at because there might be something wrong. If you determine that having these activities handled in the same controller makes for the highest overall simplicity in your solution, then do that, with as many repositories as you need in the constructor.
I can use myself as an example as to why many repositories in a controller is a bad smell. I tend to get too cute, trying to do too many things on a page or controller. I always get suspicious when I see myself putting a lot of repositories in the constructor, because I sometimes do try to cram too much into a controller. That doesn't mean it's necessarily bad. Or, maybe the code smell does indicate a deeper problem, but it not one that is too horrible, you can fix it right now, and maybe you won't ever fix it: not the end of the world.
Note: It can help minimize repositories when you have one repository per Aggregate root, rather than per Entity class.

Practical Singleton & Dependency Injection question

Say I have a class called PermissionManager which should only exist once for my system and basically fulfills the function of managing various permissions for various actions in my application. Now I have some class in my application which needs to be able to check a certain permission in one of its methods. This class's constructor is currently public, i.e. used by API users.
Until a couple of weeks ago, I would have simply had my class call the following pseudo-code somewhere:
PermissionManager.getInstance().isReadPermissionEnabled(this)
But since I have noticed everyone here hating singletons + this kind of coupling, I was wondering what the better solution would be, since the arguments I have read against singletons seem to make sense (not testable, high coupling, etc.).
So should I actually require API users to pass in a PermissionManager instance in the constructor of the class? Even though I only want a single PermissionManager instance to exist for my application?
Or am I going about this all wrong and should have a non-public constructor and a factory somewhere which passes in the instance of PermissionManager for me?
Additional info Note that when I say "Dependency Injection", I'm talking about the DI Pattern...I am not using any DI framework like Guice or Spring. (...yet)
If you are using a dependency-injection framework, then the common way to handle this is to either pass in a PermissionsManager object in the constructor or to have a property of type PermissionsManager that the framework sets for you.
If this is not feasible, then having users get an instance of this class via factory is a good choice. In this case, the factory passes the PermissionManager in to the constructor when it creates the class. In your application start-up, you would create the single PermissionManager first, then create your factory, passing in the PermissionManager.
You are correct that it is normally unwieldy for the clients of a class to know where to find the correct PermissionManager instance and pass it in (or even to care about the fact that your class uses a PermissionManager).
One compromise solution I've seen is to give your class a property of type PermissionManager. If the property has been set (say, in a unit test), you use that instance, otherwise you use the singleton. Something like:
PermissionManager mManager = null;
public PermissionManager Permissions
{
if (mManager == null)
{
return mManager;
}
return PermissionManager.getInstance();
}
Of course, strictly speaking, your PermissionManager should implement some kind of IPermissionManager interface, and that's what your other class should reference so a dummy implementation can be substituted more easily during testing.
You can indeed start by injecting the PermissionManager. This will make your class more testable.
If this causes problems for the users of that class you can have them use a factory method or an abstract factory. Or you can add a parameterless constructor that for them to call that injects the PermissionManager while your tests use another constructor that you can use to mock the PermissionManager.
Decoupling your classes more makes your classes more flexible but it can also make them harder to use. It depends on the situation what you'll need. If you only have one PermissionManager and have no problem testing the classes that use it then there's no reason to use DI. If you want people to be able to add their own PermissionManager implementation then DI is the way to go.
If you are subscribing to the dependency injection way of doing things, whatever classes need your PermissionManager should have it injected as an object instance. The mechanism that controls its instantiation (to enforce the singleton nature) works at a higher level. If you use a dependency injection framework like Guice, it can do the enforcement work. If you are doing your object wiring by hand, dependency injection favors grouping code that does instantiation (new operator work) away from your business logic.
Either way, though, the classic "capital-S" Singleton is generally seen as an anti-pattern in the context of dependency injection.
These posts have been insightful for me in the past:
Using Dependency Injection to Avoid Singletons
How to Think About the "new" Operator with Respect to Unit Testing
So should I actually require API users to pass in a PermissionManager instance in the constructor of the class? Even though I only want a single PermissionManager instance to exist for my application?
Yes, this is all you need to do. Whether a dependency is a singleton / per request / per thread or a factory method is the responsibility of your container and configuration. In the .net world we would ideally have the dependency on an IPermissionsManager interface to further reduce coupling, I assume this is best practice in Java too.
The singleton pattern is not bad by itself, what makes it ugly is the way it's commonly used, as being the requirement of only wanting a single instance of a certain class, which I think it's a big mistake.
In this case I'd make PermissionManager a static class unless for any reason you need it to be an instanciable type.

Resources