Is this dependency injection? [duplicate] - c#

This question already has answers here:
What is dependency injection?
(37 answers)
Closed 4 years ago.
Is this dependency injection if I change the below code
class Needer
{
Needed obj;
AnotherNeeded obj2;
public Needer()
{
obj = new Neede();
obj2 = new AnotherNeede();
}
}
To this code
class Needer
{
Needed obj;
AnotherNeeded obj2;
public Needer(Needed param1, AnotherNeeded param2)
{
obj = param1;
obj2 = param2;
}
}

Robert C. Martin described Dependency Injecton in his SOLID design proposal. It basically states that:
High-level modules should not depend on low-level modules. Both should depend on abstractions.
Abstractions should not depend on details. Details should depend on abstractions.
Notice a word being used a lot in that description? "Abstraction".
You get part of the problem right in your second example, you no longer manually instantiate instances of the class, you instead pass them through the constructor. This leads into a new potential problem though, what if you need a different implementation of some class (e.g a "mock" and "real" services). If your constructor took the abstractions instead of the concretes you could change the implementations in your IoC configuration.
Any sort of service or functional class should typically have an abstraction behind it. This allows your code to be more flexible, extendable and easier to maintain. So to make your second example use true dependency injection:
class Needer
{
public INeeded obj { get; set; }
public IAnotherNeeded obj2 { get; set; }
public Needer(INeeded param1, IAnotherNeeded param2)
{
obj = param1;
obj2 = param2;
}
}
Now you can have all sorts of implementations:
public class MockNeeded : INeeded
public class ApiNeeded : INeeded
etc, etc

The first option is tightly coupling the dependent class to its dependencies by newing them up in the constructor. This makes testing that class in isolation very difficult (, but not impossible).
The second option follows what is sometimes referred to as the The Explicit Dependencies Principle
The Explicit Dependencies Principle states:
Methods and classes should explicitly require (typically through method parameters or constructor parameters) any collaborating objects they need in order to function correctly.
The said, it is also usually advised to have dependent classes depend on abstractions and not concretions or implementation concerns.
So assuming that those needed classes have interfaces/abstractions that they derive from it would look like
class Needer {
private readonly INeeded obj;
private readonly IAnotherNeeded obj2;
public Needer(INeeded param1, IAnotherNeeded param2) {
obj = param1;
obj2 = param2;
}
//...
}
The allows more flexibility with the dependent class as it decouples it from implementation concerns, which allows the class to be tested in isolation easier.

the second example is DI (dependency injection).
DI is usually used with IoC (Inversion of Control)
which takes care of creating the dependencies for you based on some configuration.
have a look at autofac.
autofac

The injection doesn't happen on it's own.
Instead, there should be some kind of a factory that generates objects and uses a dependency resolver, if available.
For instance, an MVC.NET framework is that kind of a "factory", when it creates an instance of, let's say, a Controller class, it uses the DependencyResolver.Current property to populate the constructor arguments.

Related

How to provide different arguments to an object factory?

I have a library with some classes that realize the same interface:
internal class MyObj1 : IMyObj {
public MyObj1(string param1, int param2) {}
}
internal class MyObj2 : IMyObj {
public MyObj2(bool param1, string param2, int param3) {}
}
internal class MyObj3 : IMyObj {
public MyObj3(string param1, int param2) {}
}
I want to create an objects factory that allows to get access to MyObj1, MyObj2, MyObj3 only by IMyObj:
public class MyObjFactory {
public IMyObj Create<T>() {
return (IMyObj)Activator.CreateInstance(typeof(T));
}
}
I don't know how to pass constructor arguments to the factory method. Any idea?
It sounds like this is where you're at:
a) You don't want classes to create the additional classes they depend on, because that couples them together. Each class would have to know too much about the classes it depends on, such as their constructor arguments.
b) You create a factory to separate the creation of those objects.
c) You discover that the problem you had in (a) has now moved to (b), but it's exactly the same problem, only with more classes. Now your factory has to create class instances. But where will it get the constructor arguments it needs to create those objects?
One solution is using a DI container. If that is entirely familiar then that's 10% bad news and 90% good news. There's a little bit of a learning curve, but it's not bad. The 90% good news part is that you've reached a point where you realize you need it, and it's going to become an extraordinarily valuable tool.
When I say "DI container" - also called an "IoC (Inversion of Control) container," that refers to tools like Autofac, Unity, or Castle Windsor. I work primarily with Windsor so I use that in examples.
A DI container is a tool that creates objects for you without explicitly calling the constructors. (This explanation is 100% certain to be insufficient - you'll need to Google more. Trust me, it's worth it.)
Suppose you have a class that depends on several abstractions (interfaces.) And the implementations of those interfaces depend on more abstractions:
public class ClassThatDependsOnThreeThings
{
private readonly IThingOne _thingOne;
private readonly IThingTwo _thingTwo;
private readonly IThingThree _thingThree;
public ClassThatDependsOnThreeThings(IThingOne thingOne, IThingTwo thingTwo, IThingThree thingThree)
{
_thingOne = thingOne;
_thingTwo = thingTwo;
_thingThree = thingThree;
}
}
public class ThingOne : IThingOne
{
private readonly IThingFour _thingFour;
private readonly IThingFive _thingFive;
public ThingOne(IThingFour thingFour, IThingFive thingFive)
{
_thingFour = thingFour;
_thingFive = thingFive;
}
}
public class ThingTwo : IThingTwo
{
private readonly IThingThree _thingThree;
private readonly IThingSix _thingSix;
public ThingTwo(IThingThree thingThree, IThingSix thingSix)
{
_thingThree = thingThree;
_thingSix = thingSix;
}
}
public class ThingThree : IThingThree
{
private readonly string _connectionString;
public ThingThree(string connectionString)
{
_connectionString = connectionString;
}
}
This is good because each individual class is simple and easy to test. But how in the world are you going to create a factory to create all of these objects for you? That factory would have to know/contain everything needed to create every single one of the objects.
The individual classes are better off, but composing them or creating instances becomes a major headache. What if there are parts of your code that only need one of these - do you create another factory? What if you have to change one of these classes so that now it has more or different dependencies? Now you have to go back and fix all your factories. That's a nightmare.
A DI container (again, this example is using Castle.Windsor) allows you to do this. At first it's going to look like more work, or just moving the problem around. But it's not:
var container = new WindsorContainer();
container.Register(
Component.For<ClassThatDependsOnThreeThings>(),
Component.For<IThingOne, ThingOne>(),
Component.For<IThingTwo, ThingTwo>(),
Component.For<IThingThree, ThingThree>()
.DependsOn(Dependency.OnValue("connectionString", ConfigurationManager.ConnectionStrings["xyz"].ConnectionString)),
Component.For<IThingFour,IThingFour>(),
Component.For<IThingFive, IThingFive>(),
Component.For<IThingSix, IThingSix>()
);
Now, if you do this:
var thing = container.Resolve<ClassThatDependsOnThreeThings>();
or
var thingTwo = container.Resolve<IThingTwo>();
as long as you've registered the type with the container and you've also registered whatever types are needed to fulfill all the nested dependencies, the container creates each object as needed, calling the constructor of each object, until it can finally create the object you asked for.
Another detail you'll probably notice is that none of these classes create the things they depend on. There is no new ThingThree(). Whatever each class depends on is specified in its constructor. That's one of the fundamental concepts of dependency injection. If a class just receives and instance of IThingThree then it really never knows what the implementation is. It only depends on the interface and doesn't know anything about the implementation. That works toward Dependency Inversion, the "D" in SOLID. It helps protect your classes from getting coupled to specific implementation details.
That's very powerful. It means that, when properly configured, at any point in your code you can just ask for the dependency you need - usually as an interface - and just receive it. The class that needs it doesn't have to know how to create it. That means that 90% of the time you don't even need a factory at all. The constructor of your class just says what it needs, and container provides it.
(If you actually do need a factory, which does happen in some cases, Windsor and some other containers help you to create one. Here's an example.)
Part of getting this to work involves learning how to configure the type of application you're using to use a DI container. For example, in an ASP.NET MVC application you would configure the container to create your controllers for you. That way if your controllers depend on more things, the container can create those things as needed. ASP.NET Core makes it easier by providing its own DI container so that all you have to do is register your various components.
This is an incomplete answer because it describes what the solution is without telling you how to implement it. That will require some more searching on your part, such as "How do I configure XYZ for dependency injection," or just learning more about the concept in general. One author called it something like a $5 term for a $.50 concept. It looks complicated and confusing until you try it and see how it works. Then you'll see why it's built into ASP.NET Core, Angular, and why all sorts of languages use dependency injection.
When you reach the point - as you have - where you have the problems that DI solves, that's really exciting because it means you realize that there must be a better, cleaner way to accomplish what you're trying to do. The good news is that there is. Learning it and using it will have a ripple effect throughout your code, enabling you to better apply SOLID principles and write smaller classes that are easier to unit test.
I would recommend not using Activator.CreateInstance since it is relatively slow, and there is a reduction in runtime safety (e.g. if you get the number of constructor parameters wrong it will throw an exception at runtime).
I would suggest something like:
public IMyObj CreateType1(string param1, int param2)
{
return new MyObj1(param1, param2);
}
public IMyObj CreateType2(bool param1, string param2, int param3)
{
return new MyObj2(param1, param2, param3);
}
Use Activator.CreateInstance Method (Type, Object[])
Creates an instance of the specified type using the constructor that
best matches the specified parameters.
public IMyObj Create<T>(params object[] args)
{
return (IMyObj)Activator.CreateInstance(typeof(T),args);
}
Alternatively
public IMyObj Create<T>(string param1, int param2) where T : MyObj1
{
return (IMyObj)Activator.CreateInstance(typeof(T),args);
}
public IMyObj Create<T>(bool param1, string param2, int param3) where T : MyObj2
{
return (IMyObj)Activator.CreateInstance(typeof(T),args);
}
...
...

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.

Dependency injection further down the "chain"

I've been reading up on how to write testable code and stumbled upon the Dependency Injection design pattern.
This design pattern is really easy to understand and there is really nothing to it, the object asks for the values rather then creating them itself.
However, now that I'm thinking about how this could be used the application im currenty working on I realize that there are some complications to it. Imagine the following example:
public class A{
public string getValue(){
return "abc";
}
}
public class B{
private A a;
public B(A a){
this.a=a;
}
public void someMethod(){
String str = a.getValue();
}
}
Unit testing someMethod () would now be easy since i can create a mock of A and have getValue() return whatever I want.
The class B's dependency on A is injected through the constructor, but this means that A has to be instantiated outside the class B so this dependency have moved to another class instead. This would be repeated many layers down and on some point instantiation has to be done.
Now to the question, is it true that when using Dependency Injection, you keep passing the dependencys through all these layers? Wouldn't that make the code less readable and more time consuming to debug? And when you reach the "top" layer, how would you unit test that class?
I hope I understand your question correctly.
Injecting Dependencies
No we don't pass the dependencies through all the layers. We only pass them to layers that directly talk to them. For example:
public class PaymentHandler {
private customerRepository;
public PaymentHandler(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
public void handlePayment(CustomerId customerId, Money amount) {
Customer customer = customerRepository.findById(customerId);
customer.charge(amount);
}
}
public interface CustomerRepository {
public Customer findById(CustomerId customerId);
}
public class DefaultCustomerRepository implements CustomerRepository {
private Database database;
public CustomerRepository(Database database) {
this.database = database;
}
public Customer findById(CustomerId customerId) {
Result result = database.executeQuery(...);
// do some logic here
return customer;
}
}
public interface Database {
public Result executeQuery(Query query);
}
PaymentHandler does not know about the Database, it only talks to CustomerRepository. The injection of Database stops at the repository layer.
Readability of the code
When doing manual injection without framework or libraries to help, we might end up with Factory classes that contain many boilerplate code like return new D(new C(new B(), new A()); which at some point can be less readable. To solve this problem we tend to use DI frameworks like Guice to avoid writing so many factories.
However, for classes that actually do work / business logic, they should be more readable and understandable as they only talk to their direct collaborators and do the work they need to do.
Unit Testing
I assume that by "Top" layer you mean the PaymentHandler class. In this example, we can create a stub CustomerRepository class and have it return a Customer object that we can check against, then pass the stub to the PaymentHandler to check whether the correct amount is charged.
The general idea is to pass in fake collaborators to control their output so that we can safely assert the behavior of the class under test (in this example the PaymentHandler class).
Why interfaces
As mentioned in the comments above, it is more preferable to depend on interfaces instead of concrete classes, they provide better testability(easy to mock/stub) and easier debugging.
Hope this helps.
Well yes, that would mean you have to pass the dependencies over all the layers. However, that's where Inversion of Control containers come in handy. They allow you to register all components (classes) in the system. Then you can ask the IoC container for an instance of class B (in your example), which would automatically call the correct constructor for you automatically creating any objects the constructor depends upon (in your case class A).
A nice discussion can be found here: Why do I need an IoC container as opposed to straightforward DI code?
IMO, your question demonstrates that you understand the pattern.
Used correctly, you would have a Composition Root where all dependencies are resolved and injected. Use of an IoC container here would resolve dependencies and pass them down through the layers for you.
This is in direct opposition to the Service Location pattern, which is considered by many as an anti-pattern.
Use of a Composition Root shouldn't make your code less readable/understandable as well-designed classes with clear and relevant dependencies should be reasonably self-documenting. I'm not sure about unit testing a Composition Root. It has a discreet role so it should be testable.

Generic Vs Dependency injection

Is there any difference between Generic Classes and Dependency injection ? Are they not ways to implement Inversion of Control
Is generic class not a way to implement Dependency Injection with added benefits of compile time safety ?
For Example, if I have a node class, then I can define as following
class Node<T> where T : ISomeInterface
{
..
..
}
class Node
{
ISomeInterface obj
public Node(ISomeInterface inject)
{
obj = inject;
}
}
UPDATE 2
With New
class Node<T> where T : ISomeInterface, new()
{
ISomeInterface obj
public Node()
{
obj = new T();
}
}
Update 3
#akim : I have made the example that you asked for using Generics
Repository using Generics
Interface IRepository
{
public DataTable GetAll();
}
public class ProductRep : IRepository
{
public DataTable GetAll()
{
//implementation
}
}
public class MockProductRep : IRepository
{
public DataTable GetAll()
{
//mock implementation
}
}
public class Product<T> where T : IRepository, new()
{
IRepository repository = null
public Product()
{
repository = new T();
}
public List<Product> GetProduct()
{
DataTable prodlst = repository.GetAll();
//convert to List of products now
}
}
//so while using the Product class, client would Supply ProductRep class and in NUnit you //would supply MockProductRep class
Product<ProductRep> obj = new ProductRep<ProductRep>();
List<Product> lst = obj.GetProduct();
//in NUnit
Product<MockProductRep> obj = new ProductRep<MockProductRep>();
List<Product> lst = obj.GetProduct();
They are not the same. Generic types allow you to define functionality that can be applied to a wide range of other types. However when you instantiate a generic class, the compiler makes a reference to the actual types that were passed as generic parameters. So the declaration is static and cannot change after compilation. For example, I can write code that instantiates your Node class:
Node<SomeImplementation> node1 = new Node<SomeImplementation>();
Node<SomeOtherImplementation> node2 = new Node<SomeOtherImplementation>();
I am reusing your Node class in different scenarios, but once I have compiled my assembly, I cannot change the generic type of my variables (node1 and node2).
Dependency Injection (and IoC containers), on the other hand, allow you to change the functionality of your app at runtime. You can use Dependency Injection to swap out one implementation of ISomeInterface with a totally different implementation at runtime. For example, in your second node class, I can use an IoC container to create the Node class... something like:
Node n = Container.Create<Node>();
The IoC container then figures out how to instantiate the Node class based on some configuration. It determines that the constructor needs an implementation of ISomeInterface, and it knows how to build an implementation at runtime. I can change my configuration for the IoC container and execute the same assembly/code and a different implementation of ISomeInterface will be created and passed to the constructor of Node.
This is useful in unit tests, because you can mock out certain parts of your application so that one specific class can be tested. For example, you may want to test some business logic that usually accesses a database. In your unit test, you can mock your data access logic and inject new functionality that returns 'static' data that is needed to test each particular business case. This breaks your tests dependency on the database and allows for more accurate/maintainable testing.
Edit
With regards to your update, the parameter-less constructor restriction may not always be desired. You may have a class (written by you or a third party) that requires parameters. Requiring a class to implement a parameter-less constructor may effect the integrity of the application. The idea behind the DI pattern is that your Node class doesn't need to know how the class was actually created.
Suppose you had many layers of classes/dependencies. With generic types, it might look like this:
class MyClass<T>
where T : IUtilityClass
{
...
}
class UtilityClass<T> : IUtilityClass
where T : IAnotherUtilityClass
{
...
}
class AnotherUtilityClass : IAnotherUtilityClass
{
...
}
In this case, MyClass uses UtilityClass, and UtilityClass depends on AnotherUtilityClass. So when you declare MyClass, you must know every dependency down the line... not just the dependencies of MyClass, but also the dependencies of UtilityClass. This declaration looks something like this:
MyClass<UtilityClass<AnotherUtilityClass>> myTestClass =
new MyClass<UtilityClass<AnotherUtilityClass>>();
This would get cumbersome as you add more and more dependencies. With DI, your caller doesn't need to know about any of the nested dependencies because the IoC container automatically figures them out. You just do something like this:
MyClass myTestClass = Container.Create<MyClass>();
There's no need to know anything about the details of MyClass or it's utility classes.
There are usually other benefits to IoC containers as well, for example many of them provide forms of Aspect Oriented Programming. They also allow you to specify the lifetime of an object, so an object could be a singleton (only one instance will be created, and the same instance will be returned to all callers).
Generics introduce the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by code msdn. And generics with all their restrictions and check are applied during compile time using static analysis.
In other hand, Dependency injection is a software design pattern that allows a choice of component to be made at run-time rather than compile time wiki. And object coupling is bound at run time by an assembler object and is typically not known at compile time using static analysis wiki.
Answer on your question: one applied at compile time using static analysis, another applied at run time using XML or in-code configuration (it should be also valid for compile). Using Dependency injection decision about binding will be postponed until more information or configuration will be available from the context. So generics and dependency injection are different, and used for different purpose.
Sample #3 answer
Let's move one step further and provide Repository<Entity> to Controller and think about it usage. How are you going to implement controler's constructor:
public ControlFreakController<Repository<Entity>>()
{
this.repository = new Repository<Entity>(); // here is a logical problem
}
or
public ControllerWithInjection(IRepository repository)
{
this.repository = repository;
}
And how will you cover ControlFreakController with tests, if it depends on Repository<Entity> (literally hardcoded)? What if Repository<Entity> has no default constructor, and has its own dependencies and life time (for example, there should be one and only one repository rep HTTP request)? What if next day it will be required to audit work with Repository<Entity>?
I'm going to assume you mean your generic class to look like this:
class Node<T> where T : ISomeInterface {
T obj;
public Node(T inject) {
obj = inject;
}
}
..in which case, you're just opening up a generic type for dependency injection (with a restraint). You haven't discovered a different "method" of dependency injection - it is still dependency injection.
This wouldn't be very useful in a "real-world" scenario. You've made assumptions on how the type parameter would be used purely based on injecting it and restraining it. Also, you'll only ever be able to inject 1 single type of object into this, which is a very bad assumption.
After your update using new(), you've got even more issues. Your injected type must allow parameterless construction. That limits you even further.

How to inject dependencies into classes that implement an interface?

I know interfaces cannot define constructors. What is the best practice to force all classes implementing an interface, to receive their dependencies in a uniform contract. I know ints possible to inject dependencies into objects via properties, but passing them via constructors makes more sense to me. How to DI then ?
I know you said you want to have a stable contract. But an advantage to not supplying a stable interface is that your dependencies could then vary wildly with different implementations, which would reduce coupling:
public interface IBlogRepository
{
IEnumerable<Entry> GetEntries(int pageId, int pageCount);
}
class BlogDatabase : IBlogRepository
{
public BlogDatabase(ISession session)
{
this.session = session;
}
public IEnumerable<Entry> GetEntries(int pageId, int pageCount)
{
// Not that you should implement your queries this way...
var query = session.CreateQuery("from BlogEntry");
return query.Skip(pageId * pageCount).Take(pageCount);
}
private ISession session;
}
As you've said, you can also implement dependencies as properties (or arguments), but this will hard-code your dependencies, rather than making them implementation specific. You will decouple your specific session implementations, but you still have to depend on sessions.
public interface IBlogRepository
{
ISession Session { get; set; }
IEnumerable<Entry> GetEntries(int pageId, int pageCount);
IEnumerable<Entry> GetEntriesWithSession(ISession session,
int pageId, int pageCount);
}
class BlogDatabase : IBlogRepository
{
public ISession Session { Get; set; }
public IEnumerable<Entry> GetEntries(int pageId, int pageCount)
{
var query = Session.CreateQuery ...
}
public IEnumerable<Entry> GetEntries(ISession session, int pageId, int pageCount)
{
var query = session.CreateQuery ...
}
}
class BlogFile : IBlogRepository
{
// ISession has to abstract a file handle. We're still okay
// ...
}
class BlogInMemory : IBlogRepository
{
// ISession abstracts nothing.
// Maybe a lock, at best, but the abstraction is still breaking down
// ...
}
Constructor injection will only work if you're using some sort of Dependency Injection framework that can handle constructing/supplying dependencies for you. Property and argument injection will work even without the framework.
I believe all three are accepted practice. At least a couple popular frameworks support both constructor and property injection.
This means the decision is up to you as to what makes the most sense for your project. The trade-off is a dependency graph that's easy to trace, vs stronger coupling. The decision certainly doesn't have to be all-constructor or all-property/argument, either.
Another higher-level abstraction to think about is an abstract factory class. You'd do this if you want to group a set of dependencies, or you need to construct instances of them at runtime:
public interface IInstallationFactory
{
IUser CreateRegisteredUser(Guid userSid);
IPackage CreateKnownPackage(Guid id);
IInstaller CreateInstaller();
}
Various frameworks also support abstract factories.
One option is to create a method on the interface for initialization. This method can accept all of the required dependencies.
Something like:
void Configure(dependency1 value, etc.);
Of course, there are a lot of options to do this type of initialization and DI using a framework. There are a lot of options to choose from though.
Scott Hanselman has a good list here.
what you need to do is to have all your interface implementations subclass a class with a constructor taking whatever state that needs be injected. since the subclasses needs to perform a base-call, in their constructor, your constraints are uphold automatically.
at first this may seem like a strange pattern, but we use it all the time in our enterprise solutions, so I guarantee its sane :-)
We all know this is possible by many different methods, but something that makes sense is more welcome surely. I defined some set-only properties, then the object is responsible to holding a reference to what is passed to it:
public interface IBlogRepository
{
ISession Session { set; }
}
class BlogRepository : IBlogRepository
{
private ISession m_session;
ISession Session
{
set { m_session = value; }
}
}
This way every class implementing the interface knows that the set-only property is a dependency injection, since set-only properties are rarely used. I'm not sure if this method is known as a good practice or not, but for me it is, from now.
The interface is not responsible for dependencies. Only the implementation knows, what it needs to fulfill the contract.
There could be one implementation using a database, another using file system to persist data.
Which Dependency should the interface declare required? The database manager or the filesystem manager?

Categories