Enforcing dependencies in IoC via a constructor? - c#

I'm trying to come to terms with using IoC/Dependency Injection while at the same time programming to contracts rather than specific classes. The dilemma I'm having is the tension between:
Do program to interfaces for IoC: I started out with IoC relying heavily on interfaces. Judging by Spring's sample projects, interfaces are the way to go when programing to a contract with IoC.
( ... although abstract classes generally preferred: the main drawback of interfaces is that they are much less flexible than classes when it comes to allowing for evolution of APIs )
Do make class dependencies explicit via constructor
My gut feeling is that it's good programming practice to pass dependencies in to a class's constructor. Indeed, this is dependency injection.
... except you can't enforce constructor signature in interfaces/abstract clases: Neither interfaces or nor abstract classes allow for defining a constructor signature ( easily / elegantly ).
See also Framework Design Guidelines section 4.4: DO NOT define public or protected internal constructors in abstract types. ... Constructors should be public only if users will need to create instances of the type.
This question is related to a previous stackoverflow question: Interface defining a constructor signature?
But my question is:
Since you can't define a constructor in a C# interface/abstract class, as the question above asks, on a practical level:
How do you reconcile this with the sensible practice of passing dependencies in via a constructor?
Edit: Thank you for the answers. I'm hoping for some insight on what I should do in this case. Just not use contructor args? Use some sort of Init() method that does take the dependencies?
Edit2: Thanks for the great answers, very helpful.

I always think this is easier to explain with a (made up) example...
Imagine you have an ICustomerRepository interface, an IShoppingCartRepository interface and an ICheckout interface. You have concrete implementations of those interfaces - CustomerRepository, ShoppingCartRepository, and CheckoutService.
Your CheckoutService concrete class has a constructor that takes an ICustomerRepository and an IShoppingCartRepository - e.g.
public CheckoutService(ICustomerRepository customerRepository, IShoppingCartRepository shoppingCartRepository)
{
// Set fields for use in some methods later...
_customerRepository = customerRepository;
_shoppingCartRepository = shoppingCartRepository;
}
Then, when you want an ICheckoutService implementation to do some work with, you tell your IoC container which concrete class it should use for each interface type and ask it to build you an ICheckoutService. Your IoC container will go and build your classes for you, injecting the correct concrete classes into the constructor of your CheckoutService. It will also build dependencies all the way down the class heirarchy here, so if, for example your ShoppingCartRepository takes an IDatabaseSession interface in the constructor, your IoC container will inject that dependency too, as long as you have told it which concrete class to use for your IDatabaseService.
Here's some code you might use when configuring (for example) StructureMap as your IoC container (this code would typically be called during app startup):
public class AppRegistry : Registry
{
public AppRegistry()
{
ForRequestedType<ICheckoutService>().TheDefaultIsConcreteType<CheckoutService>();
ForRequestedType<ICustomerRepository>().TheDefaultIsConcreteType<CustomerRepository>();
// etc...
}
}
Then to get an instance of ICheckoutService built up and ready to go, with all the dependencies passed into the constructor for you, you would use something like:
var checkoutService = ObjectFactory.GetInstance<ICheckoutService>();
I hope that makes sense!

Your IoC container must construct an object from a concrete type, even though what you're passing around is an interface. Your constructor is not a behavior or state contract, so it does not belong in an interface or as a public member of your abstract class.
A constructor is an implementation detail, so you do not need to separate its definition from the concrete class.

You cannot define constructor signatures in interfaces. That wouldn't make sense anyway since the interface shouldn't enforce how the implementations are constructed.
Abstract classes though can indeed have constructors. They must be protected since public constructors does not make sense either. They should only be called by concrete subclasses.
The IoC principle dictates that instead of having class A know about and instantiate class B, you should instead pass in a reference to IB to the constructor of A. Then A will not need to know about class B and thus you can easily substitute class B with some other implementation of IB.
Since you're passing in an already instantiated object of class B, the IB interface doesn't need to have a constructor signature.

Related

Resolve dependency from singleton property

Let us assume I have an interface
public interface IMyInterface { }
And a class that exposes this interface as a property:
public class MyClass
{
public IMyInterface Property { get; set; }
}
MyClass is registered as a Singleton with my Windsor container. I would like to wire up the windsor container so that IMyInterface resolves to the property "Property" on the instance of MyClass, which I can achieve as follows:
container.Register(Component.For<MyClass>().ImplementedBy<MyClass>().LifeStyle.Singleton);
var myClass = container.Resolve<MyClass>();
container.Register(Component.For<IMyInterface>().Instance(myClass.Property));
However, I would prefer to have the container do all my resolving for me so I don't have to make the call to container.Resolve above. Is there a way to achieve this?
If the MyClass is responsible of creating that instance, you can't magically remove the registration for IMyInterface. You need to register something, but your configuration can be made a bit simpler by using a factory delegate as follows:
container.Register(Component.For<IMyInterface>()
.UsingFactoryMethod(() => container.Resolve<MyClass>().Property)
.LifeStyle.Transient);
If you register the IMyInterface as a singleton, there will be only one instance of the component; any resolution will return the same instance. Whether it comes from the property or not does not change the resolution
In fact this behavior by the container makes me question why it is important that you resolve through a particular accessor? Is there some additional processes in the getter to the property you've not mentioned?
Regarding the fact you don't want to resolve the MyClass to access its property, You have to retrieve an instance of the class if you don't make the property static, you won't be able to sidestep this.
Is this IMyInterface the interface from the third party library which you implement in order to use it? If this is so than I can conclude IMyInterface is 100% needed for your implementation to work.
An important note to keep in mind - Any software developer who encounters your class will not know that IMyInterface is real dependency of this class because it is a property - anybody can reset it somewhere. When you put your dependencies in ctor your are guaranteed that everybody will notice that this is a hard dependency without which the class is not supposed to work. In general - "hard" dependencies come through ctor, others may be exposed as properties.
However, in the interests of keeping the number of "moving parts" at a minumum to make the API more palatable I am happy to sacrifice a "purer" dependency injection philosophy in favour of fewer registrations.
Keep in mind that the DI principles come from practice and maintainability and readability must outweigh palatability. If somebody else maintains your code it will be easier to spot the dependency in ctor rather than as a property. Therefore palatability is an illusion because you know what your code is doing (now).
My advice is to stay with constructor injection of IMyInterface and just make a typed factory and get it through the constructor.

How to put constraint on constructor parameters in interface?

How to put constraint on constructor parameters?
Is it a good practice?
I have an interface, and I would require Logger component (to be injected by unity).
How can it be enforced that all derived classes would have Logger component (ILogger) as a parameter?
I could not find any appropriate solution.
Only workaround I have found is to put method Initialize (<parameters>) in the interface. This is an ugly approach, and requires special handling.
Is there any design pattern that address such problems?
You don't need a constraint to force derived classes to have a logger component. Just define the base class constructor to take an ILogger.
public class Foo
{
public Foo (ILogger logger) { /* some implementation here */ }
}
public class Bar : Foo
{
public Bar(ILogger logger)
: base(logger)
{
// some implementation here
}
}
Since Bar derives from Foo, it is forced to use the constructor that takes a logger. You can also make Foo abstract, which would force a user to create an instance of a derived class instead of Foo itself.
When you need to define an interface, don't just consider a C# interface. Abstract classes are perfect for cases like this. It is common to think of abstract classes as interfaces (not a C# interface). What you're asking can't be done with a C# interface because those define contracts, not implementation.
Why would you ever want to force such a thing?
Focus on what is the real contract (defined by an interface), not on such an unimportant thing like logging. The contract should be defined in a way, that you can't remove any method/property without loosing the ability to perform core functionality.
For instance if you have an interface:
interface IAdder
{
double Add(double first, double second);
}
Adding is the core functionality. You could have a third argument ILogger, but without it you can still add. Logging is the implementation detail, which should never be a part of a cotract.

Programming against an interface with only one class implementing said interface

I can understand why to program against an interface rather than an implementation. However, in an example like the following (I find this a lot):
public interface ISomething
{
void BlahOne(int foo);
void BlahTwo(string foo);
}
public class BaseSomething : ISomething
{
public void BlahOne(int foo)
{
//impl
}
public void BlahTwo(string foo)
{
//impl
}
}
public class SpecificSomethingOne : BaseSomething
{
public void SpecificOne()
{
//blah
}
}
public class SpecificSomethingTwo : BaseSomething
//and on..
The current example of this is the component based entity system in my game. (I have IComponent, Component, PosComponent, etc).
However, I cannot see a reason to have ISomething. The name may look nicer, but it doesn't seem to have a purpose. I can just return BaseSomething all the time.
Is there a reason to have an interface when you have a single base implementation everything uses? (I can see the use for, say, IComparable or IEnumerable)
EDIT: For a slightly different scenario (yet still related enough to not need a different question), if I assume I have this structure for everything, would there be much difference if I were to use ISomething for parameter types and variables compared to BaseSomething?
I prefer "lazy design" - extract the interface from BaseSomething when you need it. Until then, keep it simple and skip it.
Right now I can think of two reasons for having an interface when there is only one implementation:
There is another mock implementation for unit tests (i.e. there is a second implementation, although not in production code).
The interface and the implementation are defined in different class libraries. E.g. when using the Model-View-Presenter pattern, the view can reside in an .exe project that is dependent on the .dll where the presenter is implemented. Then an IView interface can be put in the .dll and the presenter's reference to the view supplied through dependency injection.
Correct answer to your question would be "It depends".
You can look at it in many different ways and it's all about perspective. When you have a concrete or abstract base class, it means your objects have something in common functionally. And derived objects are inter-related in some way or the other. Interfaces let you confirm to a functional contract only where each object implementing the interface will be responsible for the implementation.
Again, when you program again interfaces, you strictly know the capabilities of the object since it implements the given interface. And you need not worry about how each object functionally implements this.
It'd not be completely wrong, If I say
each of your objects are completely
independent when it comes to
implementing the interface ISomething, given that SpecificSomethingOne and SpecificSomethingTwo do not derive from BaseSomeThing and each implement their own ISomething.
You can refer to this answer on the same matter.
it is not really necessary but it is a better design if you want to extend your program later or you want to implement another Base-Class.
In your case I would not implement the Base-Class. The Interface only is just fine if you dont want to have a default-behaviour. If you want a default-behaviour then just write the Base-Class without an Interface
If your BaseSomething were abstract and you had implementing specific things that provider overloads to abstract methods, the only way to program to them at that point would be to the ISomething interface. However, in the example you showed, there is really no reason for ISomething unless you could have multiple base implementations.

Can an interface define the signature of a c#-constructor

I have a .net-app that provides a mechanism to extend the app with plugins. Each plugin must implement a plugin-interface and must provide furthermore a constructor that receives one parameter (a resource context).
During the instantiation of the plugin-class I look via reflection, if the needed constructor exists and if yes, I instantiate the class (via Reflection). If the constructor does not exists, I throw an exception that says that the plugin not could be created, because the desired constructor is not available.
My question is, if there is a way to declare the signature of a constructor in the plugin-interface so that everyone that implements the plugin-interface must also provide a constructor with the desired signature. This would ease the creation of plugins.
I don’t think that such a possibility exists because I think such a feature falls not in the main purpose for what interfaces were designed for but perhaps someone knows a statement that does this, something like:
public interface IPlugin {
ctor(IResourceContext resourceContext);
int AnotherPluginFunction();
}
I want to add that I don't want to change the constructor to be parameterless and then set the resource-context through a property, because this will make the creation of plugins much more complicated. The persons that write plugins are not persons with deep programming experience. The plugins are used to calculate statistical data that will be visualized by the app.
Thanks for all the answers.
I’ve decided, that I let it be an interface because I don’t like to force the plugin-programmers to inherit from an abstract class so that he or she loses the possibility to inherit from an own base-class. Furthermore, deriving from an abstract class does not ensure that the plugin programmer really provides the needed constructor. It makes it only more probable (The programmer has still the possibility to add only one constructor that contains the desired parameter but that also has additional parameters, and that’s also bad. See the comments to the answer of Ken Browning).
Although I mentioned in my post that I don’t want such a property, I marked the answer of Danny Varod as accepted because I think in my situation it’s the most appropriate solution. Thanks to all who answered.
Plug-in extendability is a favorite of mine...
What I do is make sure the plug-in either implements the interface or inherits the base class of the appropriate "plugin socket".
In some places base classes are more appropriate (if the plug-in is a kind of X),
in some interfaces are more appropriate (if the plug-in does IX).
I do not pass the context to the construct, instead I use a property for that and a parameterless public constructor.
This also enables easier deserialization of plug-ins using reflection.
Interfaces cannot declare constructors. You might consider using an abstract class instead.
No, this does not exist. You are probably looking for an abstract class here.
Alternatively, you might try using a factory: make the constructor signature a method signature of another type:
public abstract class PluginFactory
{
public abstract IPlugin Create(IResourceContext context);
}
and then something like (and I always mess up this part if I want it to be short, hence the edit):
public class PluginContainer
{
public IPlugin LoadPlugin<T>(IResourceContext context) where T: PluginFactory, new()
{
var factory = new T();
return factory.Create(context);
}
}
Unfortunately, interfaces in C# can only contain methods, properties, events or indexers.
You could use and abstract class that all plugins would inherit from. You'd be able to force them to implement the constructor signature in that case.
The interface can't declare / enforce a constructor.
Define the interface and create an abstract base class that provides the most likely implementation of the constructor -- probably just saving the resource context passed in.
Encourage, but don't require, plugin authors to derive from the base class. There may be other useful methods that the base class could also provide.
Continue to use reflection to check the plugins.
As others have alluded to, using an abstract class to take care of the plumbing details is a common pattern for what you're trying to accomplish. Here is one design that avoids the need for a constructor with special parameters if the consumer inherits from the abstract base class Plugin:
public interface IPlugin
{
void Initialize(IResourceContext context);
//Other methods...
}
public abstract class Plugin : IPlugin
{
protected IResourceContext Context { get; private set; }
void IPlugin.Initialize(IResourceContext context)
{
Context = context;
}
//Abstract declaration of other methods...
}
Your code has to call Initialize behind the scenes after creating the Plugin, but this detail is hidden from typical users, as they generally don't have to implement IPlugin directly. Your typical user can just define a Plugin descendant and work with the Context property.
You might also want to look into various dependency injection frameworks (such as Ninject), though they're probably overkill for what you're doing. Still, looking at how they work may give you some ideas on different ways dependency injection can be managed.

How does this "Programming to Interfaces" thing work?

I like the idea of "programming to interfaces" and avoiding the use of the "new" keyword.
However, what do I do when I have two classes that have the same interface but are fundamentally different to set up. Without going into detail about my specific code, I have an interface with a method, "DoStuff". Two classes implement this interface. One is very simple and requires no initialisation to speak of. The other has five different variables that need to be set up. When combined, they allow for literally millions of ways for the class to work when DoStuff is called.
So when do I "new" these classes? I though about using factories but I don't think they are suitable in this case because of the vast difference in setup. (BTW: there are actually about ten different classes using the interface, each allowing the formation of part of a complex pipeline and each with different configuration requirements).
I think you may be misunderstanding the concept of programming to interfaces. You always have to use the new keyword in object oriented languages to create new instances of objects. Just because you program to interfaces doesn't remove that requirement.
Programming to an interface simply means that all your concrete classes have their behavior defined in an interface instead of in the concrete class itself. So when you define the type of a variable, you define it to be the interface instead of a concrete type.
In your case, just implement DoStuff in your concrete classes as each class needs it implemented (whether doing it simply or with 10 other initialized objects and setup). For example, if you have an interface IInterface and class SomeClass which implements IInterface. You might declare an instance of SomeClass as such:
IInterface myInstance = new SomeClass();
This allows you to pass this instance around to other functions without having to have those functions worry about the implementation details of that instance's class.
Well you really have 3 options. Use new, use a factory or use an DI container. With a DI container your five variables would most likely need to be in a configuration file of some sorts.
But to be completely honest it sounds like you're making your life harder than it needs to be by forcing yourself into a corner. Instead of coding to some ideal, rather code in a manner which best facilitates solving the problem at hand. Not saying you should do a hack job of it, but really, saying you don't want to use new, that is really making your life harder than it needs to be...
Regardless of what you use, at some point you're going to have to construct instances of your classes in order to use them, there's no way around that.
How to go about doing that depends on what you want to accomplish, and the semantics of those classes.
Take the class you mention with those fields.
Can those fields be read from somewhere? A configuration file, as an example? If so, perhaps all you need is just a default constructor that initializes those fields from such a configuration file.
However, if the content of those fields really needs to be passed in from the outside world, there's no way around that.
Perhaps you should look at a IoC container and Dependency Injection?
If you are passing that many configuration parameters into your class it may have too many responsibilities. You should look into breaking it up into smaller classes that only have a single responsibility.
Avoiding the new keyword can be valuable because it creates a dependancy on the implementing class. A better solution would be to use Dependancy Injection.
for example
public interface IDoStuff
{
void DoStuff();
}
public class DoStuffService
{
private IDoStuff doer;
public DoStuffService()
{
//Class is now dependant on DoLotsOfStuff
doer = new DoLotsOfStuff(1,true, "config string");
}
}
public class DoStuffBetterService
{
private IDoStuff doer;
//inject dependancy - no longer dependant on DoLotsOfStuff
public DoStuffBetterService(IDoStuff doer)
{
this.doer = doer;
}
}
Obviously you still have to create the IDoStuff object being passed in somewhere.
An Inversion of Control (IoC) container is a good tool to help with implementing this.
Here is a good tutorial for Castle Windsor Container if you are interested in learning more. (There are many other IoC containers, I just happen to use this one.)
The example in your question was very abstract, so I hope this answer is helpful.
If I understand you correctly the problem is with different initialization. You need to provide for two classes that have the same interface. One does not need anything, and the other needs some paramaters and calls some complex initialization.
You should use have a constructor that gets InitializationParameter. Both classes should get it. One with a simple interface that does not need to get anything from it. The other that needs params and will get them from it.
If you are concerned about initialization you can use factory, just ask it for some interface providing this init parameter and factory will create, init and return to you the object according to the values you provided.
If something is not clear - please ask.

Categories

Resources