For the sake of this example, I have a "User" class that needs to receive access to my EmailService.
Whenevera a new user instance is created ( var user = new User(emailServiceInstance); ) I do not want EmailService instance to be included as a parameter because not all callers will be aware of it. I want Ninject to inject it.
So normally a binding for the EmailService would look something like this:
kernel.Bind<IEmailService>().To<EmailService>().InSingletonScope();
But I would like to include more parameters in my User class constructor. I would like to pass some parameters and have EmailService injected as well. Is this possible?
From its callers, User class would be instanciated with something like:
var user = new User(firstName,LastName, [notsure])
And then my User class constructor would look like this:
public User(string firstName, stringLastName, EmailService emailService)
First and Lastname would be passed in and email service would be instantiated/injected with Ninject.
Is it possible? What would be the correct syntax to create this binding ?
Neither Constructor Injection nor Property Injection are a good fit for your scenario. In section 4.3 of DIPP&P, Mark Seemann and I state that:
Entities that contain behavior besides their usual set of data members would easily get a wide range of methods, each requiring their own dependencies. Although you might be tempted to use Constructor Injection to inject such dependencies, that leads to a situation where each such entity needs to be created with all of its dependencies, even though only a few may be necessary for a given use case. This complicates testing the logic of an entity, because all dependencies need to be supplied to the constructor, even though a test might only be interested in a few dependencies. Method Injection [...] offers a better alternative.
Using Method Injection, your User entity would become something as follows:
public class User
{
public string FirstName { get; }
public string LastName { get; }
public string PasswordHash { get; }
public User(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
public void ResetPassword(
IEmailService mailService, IPasswordGenerator generator)
{
var password = generator.Generate();
this.PasswordHash = generator.Hash(password);
// Warning: this is just an example, but not a good security practice.
// Mailing passwords is a good way to be shamed on plaintextoffenders.com
mailService.SendMail($#"
Hello {this.FirstName}
We have received new password request for your account.
Your new password is: {password}.");
}
}
Notice that the ResetPassword method does not store its incoming dependencies. This is deliberate and this is what makes Method Injection different from both Constructor Injection and Property Injection. When dependencies are applied to a class after construction (which is what happens with Property Injection), it leads to Temporal Coupling. By letting the method use the dependency, but not store the dependency, it prevents Temporal Coupling from occurring.
A more detailed discussion about Method Injection and how to apply it to classes like entities can be found in section 4.3 of Dependency Injection Principles, Practices, and Patterns.
Related
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");
I have two classes and have one to many relationship as shown below
public class User
{
public string Name{get;set;}
public IList<Address> Addresses{get;set}
}
public class Address
{
public string StreetAddress{get;set;}
public User User{get;set;}
}
To add address to user I need to initiate Addresses property in User constructor as
public User()
{
this.Addresses=new List<Address>();
}
Is this scenario good candidate to use DI to initiate List or should I initiate the Address list in constructor as shown.
If the the address data itself is required to construct an instance of User, it may be a candidate for DI. But if's just a matter of making sure the list is instantiated, then your code is correct as-is.
In this case Dependency Injection would be overkill. Dependency Injection is usually used to initialize complex networks of services. Here you are dealing with a network of data objects that map to the piece of world you are translating into code: a composition between User and Address is therefore sufficient, and you must initialize collections in the constructor.
I'm learning about Domain-Driven-Design and I'm a little confused about entities and injecting domain services into them. I have found this blog and conclusion is that injecting services into entities is a bad idea. I partially agree with that, but what to do in this case:
I have User entity which is an aggregate root, which has Password value object in it. It look like this:
Password value object:
public class Password
{
public string Hash { get; private set; }
public string Salt { get; private set; }
private readonly IHashGeneratorService _hashGeneratorService;
public Password(IHashGeneratorService hashGeneratorService)
{
_hashGeneratorService = hashGeneratorService;
}
public void GenerateHash(string inputString)
{
//Some logic
Salt = hashGeneratorService.GenerateSalt();
Hash = hashGeneratorService.GenerateHash(inputString);
}
}
User entity:
public class User
{
public Password Password { get; private set; }
public User(IHashGeneratorService hashGeneratorService)
{
this.Password = new Password(hashGeneratorService);
}
}
In this case if I create User entity via factory I need to provide IHashGeneratorService implementation to factory constructor or Create() method. After that if my factory is used by, for ex. SomeUserService I have to provide implementation (ex. via ctor injection) to it. And so on...
Honestly it smells form me, as lot of my classess are dependent on hash generator service implementation but only Password class uses it. And it also breaks SRP principle for Password class as I assume.
I've found out some solutions:
Use service locator. But it also smells as it's an anti-pattern and it is hard to test and manage entities if we use it.
Implement hashing alghoritm directly inside Password methods.
Stay with that what I have :) Cons are mentioned above, pros are that my classess are easier to test as I can provide mocked service instead of full implementation.
Personally I tend to refoactor my code to second solution as it does not break SRP (or it does? :)), classess are not dependent of hashing service implementation. Something more?
Or do you have another solutions?
I am quite new to DDD, however I belive that hashing passwords is not a concern of the domain, but a technical concern, just like persistence. The hash service should have it's interface defined in the domain, but it's implementation in the infrastructure layer. The application service would then use the hash service to hash the password and create a Password instance (which should be a value object) before passing it to the User aggregate root.
There might be cases where an aggregate has to use a service like when the dependency resolutions are very complex and domain-specific. In this case, the application service could pass a domain service into the aggregate method. The aggregate would then double-dispatch to the service to resolve references.
For more information you can read the Implementing Domain-Driven Design book written by Vaughn Vernon. He speaks about this around page 362 (Model Navigation), but also at a few other places in the book.
I don't know reasons, why do you consider injection of constructor parameters only. AFAIK, it's a common feature for DI-containers to inject properties or fields. E.g., using MEF you could write something like this:
class SomeUserService : ISomeUserService
{
[Import]
private IHashGeneratorService hashGeneratorService { get; set; }
// ...
}
and inject a dependency only in those types, where you really need it.
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.
I'm using C# with Microsoft's Unity framework. I'm not quite sure how to solve this problem. It probably has something to do with my lack of understanding DI with Unity.
My problem can be summed up using the following example code:
class Train(Person p) { ... }
class Bus(Person p) { ... }
class Person(string name) { ... }
Person dad = new Person("joe");
Person son = new Person("timmy");
When I call the resolve method on Bus how can I be sure that the Person 'son' with the name 'timmy' is injected and when resolving Train how can I be sure that Person 'dad' with then name 'joe' is resolved?
I'm thinking maybe use named instances? But I'm at a loss. Any help would be appreciated.
As an aside, I would rather not create an IPerson interface.
Unless you register respectively "joe" and "timmy" as named dependencies, you can't be sure that "timmy" is injected into Schoolbus. In fact, if you attempt to register two instances of the same class as unnamed dependencies, you will have an ambiguous setup, and you will not be able to resolve Person at all.
In general, if you have to register a lot of named instances you are probably going about DI in the wrong way. The main idea of DI is to resolve Domain Services more than Domain Objects.
The primary idea of DI is to provide a mechanism that allows you to resolve abstract types (interfaces or abstract classes) into concrete types. Your example has no abstract types, so it doesn't really make a lot of sense.
One way to solve this would be to use an injection constructor with a named registration.
// Register timmy this way
Person son = new Person("Timmy");
container.RegisterInstance<Person>("son", son);
// OR register timmy this way
container.RegisterType<Person>("son", new InjectionConstructor("Timmy"));
// Either way, register bus this way.
container.RegisterType<Bus>(new InjectionConstructor(container.Resolve<Person>("son")));
// Repeat for Joe / Train
Mark Seeman got it right. And I sympathize with your confusion. I went through it myself when I learned to use automatic dependency injection containers. The problem is that there are many valid and reasonable ways to design and use objects. Yet only some of those approaches work with automatic dependency injectorion containers.
My personal history: I learned OO principles of object construction and Inversion Of Control long before I learned how to use Inversion of Control containers like the Unity or Castle Windsor containers. I acquired the habit of writing code like this:
public class Foo
{
IService _service;
int _accountNumber;
public Foo(IService service, int accountNumber)
{
_service = service;
_accountNumber = accountNumber;
}
public void SaveAccount()
{
_service.Save(_accountNumber);
}
}
public class Program
{
public static void Main()
{
Foo foo = new Foo(new Service(),1234);
foo.Save();
}
}
In this design, my Foo class is responsible for saving accounts to the database. It needs an account number to do that and a service to do the dirty work. This is somewhat similar to the concreted classes you provided above, where each object takes some unique values in the constructor. This works fine when you instantiate the objects with your own code. You can pass in the appropriate values at the right time.
However, when I learned about automatic dependency injection containers, I found that I was no longer instantiating Foo by hand. The container would instantiate the constructor arguments for me. This was a great convenience for the services like IService. But it obviously does not work so well for integers and strings and the like. In those cases, it would provide a default value (like zero for an integer). Instead, I had been accustomed to passing in context-specific values like account number, name, etc... So I had to adjust my style of coding and design to be like this:
public class Foo
{
IService _service;
public Foo(IService service)
{
_service = service;
}
public void SaveAccount(int accountNumber)
{
_service.Save(accountNumber);
}
}
public class Program
{
public static void Main()
{
Foo foo = new Foo(new Service());
foo.Save(1234);
}
}
It appears that both Foo classes are valid designs. But the second is useable with automatic dependency injection, and the first is not.