Is this basically what an IOC like NInject does? - c#

Normally I would do this:
public class DBFactory
{
public UserDAO GetUserDao()
{
return new UserDao();
}
}
Where UserDao being the concrete implementation of IUserDao.
So now my code will be littered with:
DBFactory factory = new DBFactory();
IUserDao userDao = factory.GetUserDao();
User user = userDao.GetById(1);
Now if I wanted to swap implementaitons, I would have to go to my DBFactory and change my code to call a different implementation.
Now if I used NINject, I would bind the specific implementation on application startup, or via a config file. (or bind based on specific parameters etc. etc.).
Is that all there is too it? Or is there more?
(reason I am asking if I want to know how it will help me here: Help designing a order manager class)

In a word, yes. Your code would then change in structure, so your dependencies would be passed in via the constructor (or setters, which I am personally not a fan of). You would no longer say "new XXX()" for services in the body of your methods.
You also would not likely need the factory anymore at all, since the DI framework can act as a factory. You would likely just need a constructor dependency on IUserDAO.
So something like:
public class ClassThatNeedsUserDAO
{
private readonly IUserDAO _userDAO;
public ClassThatNeedsUserDAO(IUserDAO userDAO)
{
_userDAO = userDAO;
}
public User MyMethod(userId)
{
return _userDAO.GetById(int userId);
}
}

There is more to it, one example would be if the constructor of UserDao required some other objects to be passed as arguments (dependencies).
You could have ninject automatically create and inject those objects, saving some lines of code but more importantly ensuring that every class is loosely coupled with its dependencies.

Related

Why using the factory pattern when a simple dependecy injection is enough

Im looking to this example to understand the use of factory pattern.
I'm really amator in this field so excuse my silly question.
My problem is that i don't see the use of the factory pattern which return us the interface that we can inject it directly when we need to use it.
In the example above I would do something like this:
public class Program
{
// register the interfaces with DI container in a separate config class (Unity in this case)
private readonly IShippingStrategy _shippingStrategy;
public Program(IShippingStrategy shippingStrategy)
{
_shippingStrategy= shippingStrategy;
}
public int DoTheWork(Order order)
{
// assign properties just as an example
order.ShippingMethod = "Fedex";
order.OrderTotal = 90;
order.OrderWeight = 12;
order.OrderZipCode = 98109;
int shippingCost = _shippingStrategy.CalculateShippingCost(order);
return shippingCost;
}
}
Instead of injecting the factory :
public class Program
{
// register the interfaces with DI container in a separate config class (Unity in this case)
private readonly IShippingStrategyFactory _shippingStrategyFactory;
public Program(IShippingStrategyFactory shippingStrategyFactory)
{
_shippingStrategyFactory = shippingStrategyFactory;
}
public int DoTheWork(Order order)
{
// assign properties just as an example
order.ShippingMethod = "Fedex";
order.OrderTotal = 90;
order.OrderWeight = 12;
order.OrderZipCode = 98109;
IShippingStrategy shippingStrategy = _shippingStrategyFactory.GetShippingStrategy(order);
int shippingCost = shippingStrategy.CalculateShippingCost(order);
return shippingCost;
}
}
Why taking the bruden to create a factory (thus adding an extra layer) when we can inject the interface directly to wherever we need to use it ?
I think you don't want just another article about the factory pattern but a short comprehensive answer.
So, I'd like to focus on two things.
More flexibility
Most commonly, you'd set up your composition root where you basically say ...
"if anyone wants IAnyService, he should get MyAnyServiceImplementation".
This is fixed for your application. Once set up, your dependency injection container will serve the class instances you registered but you should not try to re-configure that container again. That's perfect for startup flexibility like registering implementation for data access components by the application's configuration, for example. Say ...
"if anyone wants IUserRepository, he should get MsSqlUserRepository because we are working with MSSQL server".
Of course, having that "immutable" composition root limits the possibilities to choose an implementation in runtime depending of the applications' state.
Instead you can inject a class which decides on a current state which service implementation to choose. Data validation is a typical scenario for that pattern because there might be different rules for different entities on your system. The buzzword here is "rule pattern" or "strategy pattern".
Lifetime control
Think of a long-living class instance like a view (user interface) or any class attached to it (like a viewmodel or a controller). As long as a user is active on a view, the class is alive. By injecting a class instance to the constructor of the view controller, for example, you hold an active instance of it as long as the view lives.
Let's say you want to use a data repository to connect to a database for example. These database access calls should be short and you do not want to keep connections open for a long time. With a repository factory, you could control the lifetime very precisely and make sure that the class is removed after it has been used:
using (var repository = new _factory.CreateRepository(...))
{
return repository.GetAnything();
}
With this, a very lightweight class - the factory - gets injected and lives as long as the view controller lives. The heavy classes - the connection things - should not live long and are just created when needed.
In fact, chances are that the repository is not instantiated at all if there's no requirement to load the data (because of an upfront cache hit, for example). If you would have injected the repository directly, you'd guarantee that one long living instance lives in memory in every case.
If you check the code for the factory you can see that depending on the ShippingMethod of the order a different implementation of the IShippingStrategy is returned by the factory. Since the ShippingMethod is only known once DoTheWork has been called it's impossible to inject the right implementation when the class is constructed (and the same class might even need different implementations for different orders).

How to create a class without constructor parameter which has dependency injection

I have added the dependency injections to the project. But when i create an instance by using new keyword, dependency injection doesn't work.
public class MyClass
{
ILoginTokenKeyApi _loginTokenKeyApi;
public MyClass(ILoginTokenKeyApi loginTokenKeyApi)
{
_loginTokenKeyApi = loginTokenKeyApi;
}
...
}
When i try to create an instance of MyClass, it wants a parameter to be constructed naturally.
Just like this :
MyClass mc = new MyClass(); // ERROR, it wants a parameter (but it is what i want)
I have to do :
MyClass mc = new MyClass(new LoginTokenKeyClass()); // this is not a good code for me
How i create an instance of MyClass without parameter because it has dependency injected.
But when i create an instance by using new keyword, dependency injection doesn't work.
That’s fundamentally how dependency injection works.
With dependency injection, you are simply not supposed to new up new objects. That’s the whole point of dependency injection and inversion of control. Instead of creating objects and managing those objects’ dependencies, you are depending on the framework to give you the dependencies you need without having you to care about where they actually come from and how they are constructed properly. So you are moving the responsibility to create the object up to the caller.
If you find yourself in need to create an object that has a dependency, then this is a clear sign that you are doing it wrong. A common reason for this is that you want to create the object in order to manage its lifetime, or because it is actually a data object that just happens to have some operations that needs other dependencies to work (e.g. an entity that has a “save” method). In the first case, you simply don’t do it like that. You just depend on it and let the framework manage the lifetime; if it has an incorrect lifetime, then you should reconfigure it with the DI container.
In the latter case where you have a data object with operations, you should split this up. You should just have a data object, without any logic, and then inject some manager service that is able to perform the operation on that data object for you.
For example in ASP.NET Core Identity, you have the User object which is just a normal entity without any logic. In order to e.g. add user roles or change the password, you rely on the user manager which you can inject. So the User object itself is without any dependencies.
I’d generally suggest you to read the dependency injection chapter of the ASP.NET Core documentation to understand how dependency injection works and how it is supposed to be used within the framework.
As mentioned in the comments, it is not clear what you trying to achieve, but in order to do DI in .Net Core you have to create an interface IMyClass, then let your class implement that interface,
public interface IMyClass {
void SampleMethod();
}
public class MyClass : IMyClass
{
ILoginTokenKeyApi _loginTokenKeyApi;
public MyClass(ILoginTokenKeyApi loginTokenKeyApi)
{
_loginTokenKeyApi = loginTokenKeyApi;
}
public void SampleMethod()
{
// method logic goes here...
var xx = _loginTokenKeyApi.WhatEver;
}
}
then register ILoginTokenProvider and IMyClass in startup.cs
services.AddTransient<ILoginTokenProvider, LoginTokenProvider>();
services.AddTransient<IMyClass, MyClass>();
finally inject IMyClass where you need it:
public class IndexModel : PageModel {
private readonly IMyClass _myClass;
public IndexModel(IMyClass myClass)
{
_myClass = myClass;
}
public void OnGet()
{
_myClass.SampleMethod();
}
}
btw, it is also possible to register and inject MyClass without implementing IMyClass interface, but I prefer to follow basic programming principals :)
There are two types of Dependency Injections.
Constructor Injection - which you dont want
Property Injection - In this - you expose Public Get/Set property of the Object you want to be injected. And then in your DI config file (like spring.net) you can assign values.
Another way you can do DepInjection is that in the param less constructor - you can get the Object by a Key/Name. Like in Spring.Net we would do:
var UtilityObject = Spring.ContextRegistry.GetContext().GetObject("MyUtilObject") as TheUtilityClass;

TDD - How would a concrete implementation be provided the concrete version of factory logic?

For the example, we have a ShipmentInformationModelFactory, it's purpose is to populate a model and return it.
internal class ShipmentInformationModelFactory
{
private IGetCarrierServiceFactory getCarrierServiceFactory;
public ShipmentInformationModelFactory(IGetCarrierServiceFactory getCarrierServiceFactory)
{
this.getCarrierServiceFactory = getCarrierServiceFactory;
}
internal ShipmentInformation Create(ICarrierTransaction carrierTransaction, CarrierPackage carrierPackage)
{
ShipmentInformation shipmentInformation = new ShipmentInformation();
// Get the Carrier Service Model for the ID of the carrier service against the Package.
ICarrierServiceModel carrierServiceModel = this.getCarrierServiceFactory.Get(carrierPackage.CarrierServiceId);
shipmentInformation.ServiceCode = carrierServiceModel.Code;
return shipmentInformation;
}
}
We then have a MockGetCarrierServiceFactory which just returns some stub data.
[TestMethod]
public void CreateShipmentInformation_ShipmentData()
{
ShipmentInformationModelFactory shipmentInformationModelFactory = new ShipmentInformationModelFactory(new MockGetCarrierServiceFactory());
ShipmentInformation shipmentInformation = shipmentInformationModelFactory.Create();
}
internal class MockGetCarrierServiceFactory : IGetCarrierServiceFactory
{
public ICarrierServiceModel Get(int carrierServiceModelID)
{
ICarrierServiceModel carrierServiceModel = Mock.Create<ICarrierServiceModel>();
Mock.Arrange(() => carrierServiceModel.Code).Returns("TestCarrier");
Mock.Arrange(() => carrierServiceModel.Description).Returns("TestDescription");
return carrierServiceModel;
}
}
This works wonderful and I feel like it follows SOLID principles quite well, please feel free to correct me if I'm wrong.
My problem comes with the (live) concrete version of this implementation. At which point should the concrete version of GetCarrierServiceFactory be passed into ShipmentInformationModelFactory?
Should I do down the route of creating a default constructor and having it auto populated inside there?
The class which instantiates the ShipmentInformationModelFactory object could pass provided it into the constructor but I've just created a dependency there.
I feel like I'm understanding TDD and SOLID principles 80% but am getting lost when it comes to the creation of these factories.
The class which instantiates the ShipmentInformationModelFactory object could pass provided it into the constructor but I've just created a dependency there.
You have to have dependencies. ShipmentInformationModelFactory is dependent on a concrete implementation of IGetCarrierServiceFactory. The key is to avoid those dependencies becoming couplings.
If you go for the default constructor route, then you hard code that dependency within ShipmentInformationModelFactory, thus tightly coupling the two.
So the solution is to provide that dependency at application start-up. From the start point of your code, either use an IoC container to fulfil those dependencies, or use pure DI (ie, write your own mapping code).
That way, the two classes remain loosely coupled and your testing approach still works, but you can also wire up the real dependencies in the application itself.

Is there any practical usage of using unity container to add, resolve dependencies in the controller itself?

In the MVC application i am working with these days, they have registered and resolved all the Interface/Concrete class dependencies inside the controller itself. I read about ioc and dependency inversion and found that the thing that has been done is completely non-useful. Since it would anyway not allow the application to leverage benefits of IoC example mocking, unit testing and would also add cost of adding/resolving the dependencies unnecessarily. Below is code sample:
HomeController
using(IUnityContainer container= new UnityContainer())
{
container.RegisterType<IRepository1, Repository1>()
IRepository1 _repos1 = container.Resolve<IRepository1>();
}
I dont see any point of doing all this stuff if we dont get any benefit out of this. Can someone please tell if this could be of any use now or in future?
If not, i am planning to simply instantiate them with concrete implementations or like:
IRepository1 repos1= new Repository1();
Please ignore the syntax.
(I have editted the code snippet now.)
Using a container to first register and then resolve a concrete type doesn't make any sense, there is no benefit of that. You are still coupled to a concrete type. You could possibly argue that the container helps to match all constructor parameters with instances of respective types but this doesn't count as a real benefit in my opinion.
If you really don't plan to make use of abstractions that are resolved externally, then yes, you can safely remove the bloating container code and create concrete instances, just as you have presented.
The immediate answer to this question is your current implementation causes more overhead and performance impact then doing a standard construction, and you should remove it; or redesign your implementation of Unity.
The following is an example of the benefit of injection that occurs when resolving to a type that has a dependency of another type that is registered with the unity container.
public class UserService
{
internal readonly IRepository _repository;
public UserService(IRepository repository)
{
_repository = repository;
}
//Service Method that exposes 'Domain Logic'
public void CreateUser(string FirstName)
{
_repository.Insert<User>(new User() { FirstName = FirstName }); //Assumes there is a Generic method, Insert<T>, that attaches instances to the underline context.
}
public User GetUser(string FirstName)
{
return _repository.Query<User>().FirstOrDefault(user => user.FirstName == FirstName); // assumes there is a Generic method, Query<T>, that returns IQueryable<T> on IRepository
}
}
register the types (probably in a singleton pattern at Global.asax)
//Resolver is an instance of UnityContainer
Resolver.RegisterType<IRepository, Repository>(new ContainerControlledLifetimeManager());
Resolver.RegisterType<IUserService, UserService>();
Then the logic in your controller is like so:
var service = Resolver.Resolve<IUserService>(); //the resolver will resolve IRepository to an instance as well...
var user = service.GetUser("Grant");

Dependency injection with factory for child class with constructor argument

I've got this app that uses Ninject for DI and I've got the following construction:
public class SomeServicHost
{
private ISomeService service;
public SomeServicHost(ISomeService service)
{
this.service = service;
}
public void DoSomething(int id)
{
// Injected instance
this.service.DoWhatever("Whatever");
// Without injection - this would be how it would be instantiated
var s = new SomeService(new Repo(id));
s.DoWhatever("Whatever");
}
}
interface ISomeService
{
void DoWhatever(string id);
}
class SomeService : ISomeService
{
private IRepo SomeRepo;
public SomeService(IRepo someRepo)
{
this.SomeRepo = someRepo;
}
public void DoWhatever(string id)
{
SomeRepo.DoSomething();
}
}
interface IRepo
{
void DoSomething();
}
class Repo : IRepo
{
private int queueId;
public Repo(int queueId)
{
this.queueId = queueId;
}
public void DoSomething()
{
// Whatever happens
}
So normal injection is not going to work. I'm going to need a factory. So I could do something like:
interface IServiceFactory
{
ISomeService GetService(int id)
{
return new SomeService(new Repo(id));
}
}
Which I acually have already. But if I do that, I lose all of the DI goodness, like lifecycle management, or swap out one implementation with another. Is there a more elegant way of doing this?
Keeping the factory as you describe it, seems fine to me. That's what they are for, when you have services that can only be instantiated at runtime depending on some runtime value (like id in your case), factory is the way to go.
But if I do that, I lose all of the DI goodness, like lifecycle
management, or swap out one implementation with another.
DI is not an alternative for factories. You need both worlds which lead to a flexible, loosely coupled design. Factories are for new-ing up dependencies, they know how to create them, with what configuration and when to dispose them, and if you want to swap implementations, you still change only one place: only this time it's the factory, not your DI configuration.
As a last note, you might be tempted to use the service locator anti-pattern, as proposed in another answer. You'll just end up with worse design, less testable, less clear, possibly tightly coupled with you DI container and so on. Your idea for using a factory is far better. (here are more examples, similar to yours).
Instead of doing
new SomeService(new Repo(id));
you can do
IResolutionRoot.Get<Repo>(new ConstructorArgument("id", id));
IResolutionRoot is the type resolution interface of the kernel, and you can have it constructor injected. This will allow you to benefit from the "DI goodness", as you called it. Please note that you might also want to use the ninject.extensions.contextpreservation extension.
The ninject.extensions.factory, that #Simon Whitehead pointed out already, helps you eliminate boiler plate code and basically does exactly what i've described above.
By moving the IResolutionRoot.Get<> call to another class (.. factory...) you unburden SomeService from the instanciation. the ninject.extension.factory does exactly that. Since the extension does not need an actual implementation, you can even save yourself some unit tests! Furthermore, what about if SomeService is extended and requires some more dependencies, which the DI manages? Well no worries, since you are using the kernel to instanciate the class, it will work automatically, and the IoC will manage your dependencies as it should.
If you wouldn't be using DI to do that instanciation, you might end up with using very little DI at the end.
As #zafeiris.m pointed out this is called Service Locator. And is also often called an anti pattern. Rightly so! Whenever you can achieve a better solution, you should. Here you probably can't. Suffice it to say it's better so stick with the best solution no matter what people call it.
There may be ways to cut down on the usage of service location. For example, if you have a business case, like "UpdateOrder(id)", and the method will create a service for that ID, then another service for that ID, then a logger for that ID,.. you may want to change it to creating an object which takes the ID as inheritable constructor argument and inject the ID-specific services and logger into that object, thus reducing the 3 factory/service locator calls to 1.

Categories