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.
Related
I am using the Microsoft.Extensions.DependencyInjection 5.0.1 nuget package.
Here's the Dependency Injection service that I created:
public partial class BehaviorService : IBehaviorService
{
public BehaviorService()
{
}
public class MyClass : MyClassBase
{
public void MyMethod()
{
}
}
}
public interface IBehaviorService
{
}
As MyClass inherits from MyClassBase, I was thinking it was best to put that inside of a service—but I am very new to DI, so maybe it should be it's own service? I hope I can get advice here.
What I am not sure how to do is access the method inside the MyClass class that's inside of my BehaviorService, and how can I identify that in my interface?
Note: To access the service, I was thinking to use something like:
var x = Startup.ServiceProvider.GetRequiredService<BehaviorService>();
There are a few conceptual problems here that you’re going to run into. I’m going to approach the problem from the outside in, eventually getting down to your specific question. The short answer to your immediate question, though, is that you either need to register and consume MyClass as its own service, or you need to instantiate and expose it from BehaviorService, and communicate that via your IBehaviorService interface. Before you get there, though, you’ll want to work through the broader conceptual problems discussed below.
Constructor Injection
Your dependencies should be passed into consuming class via the constructor, and wired up by your dependency injection container (i.e., the Microsoft dependency injection library). You should not call out to your dependency injection container from within your consuming class—by e.g. calling GetRequiredService()—as that just establishes a hard-coded dependency on your dependency injection container itself, while also obscuring the dependencies of your application from external callers.
Note: Calling to your dependency injection container from within a consuming class is known as the service locator pattern, and it’s usually regarded as an anti-pattern.
Code to Interfaces
The dependency passed into your consuming class’s constructor should be your IBehaviorService interface, and that’s all your consuming class should ever be aware of. That means your consuming class has no awareness of implementation details that are specific to your concrete BehaviorService class unless they’re reflected in the IBehaviorService interface. This allows you to swap out implementations without maintaining a dependency on any one concrete implementation—which is the primary goal of dependency injection. Currently, your IBehaviorService contains no members, so there’s nothing consuming classes can do to interact with it.
Note: Acknowledging that part of your question is how to expose your nested method via your interface—I’ll circle back to that below.
Accessing a Nested Class
There are three basic ways of accessing your nested MyClass class:
Establish an interface for it, register it with your dependency injection container, and inject it into a consuming class via the injector—i.e., to treat it exactly like an independent service.
Do the same as the above, but inject it into BehaviorService instead of your consuming class. That makes sense if BehaviorService relies on MyClass, but your consuming class doesn’t—which doesn’t sound like the case here.
Have your parent BehaviorService class create and expose an instance of MyClass via a member registered on the IBehaviorService. In this case, that member needs to be added to your IBehaviorService interface.
Of these, the first should be your preference unless BehaviorService depends on MyClass, in which case the second should be your preference. If both your consuming class and BehaviorService depend on MyClass then it should be injected into both. Finally, there are a lot of potential issues with the last option, so I’d avoid it; if you need to expose another class from a dependency, it should either be a well-known class (e.g., in the same project as your interface), or should adhere to an interface or base class which is.
Nested Classes vs. Services
Critically, in any of these cases, there is no real need or benefit to having MyClass nested; the same options are available if it were a separate class. From dependency injection’s perspective, it doesn’t really matter either way. So the question you should be asking yourself is what problem are you trying to solve by nesting it?
(Personally, I very rarely find cases where a nested classes are desirable—and especially public nested classes—but I don’t know your use case.)
Accessing Just a Nested Method
The above assumes you want to access the nested class. If you really only care about the method on the nested class, and only need it it context of your service, then the simpler approach is for your interface expose that method:
public interface IBehaviorService
{
void MyMethod();
}
And then have your BehaviorService proxy a request to an instance of the nested class:
public partial class BehaviorService : IBehaviorService
{
private readonly MyClass myClass;
public BehaviorService()
{
myClass = new MyClass();
}
public void MyMethod() => myClass.MyMethod();
private class MyClass : MyClassBase
{
public void MyMethod()
{
}
}
}
In this case, neither your interface or your consumers need to be aware of the existence of the nested class—and, in fact, you might even be able to mark it as private. Your BehaviorService is effectively acting as a facade to the nested class. This works well if a) MyClass is really specific to your BehaviorService implementation, and/or b) you only need access to a couple of members of MyClass.
How do I register types which take another registered type as a parameter and also simple types (like an integer)?
public interface IDeviceManager
{
// implementation omitted.
}
public class DeviceManager : IDeviceManager
{
public DeviceManager(IDeviceConfigRepository configRepo, int cacheTimeout)
{
// implementation omitted
}
}
I do have a container registration for the IDeviceConfigRepository. That's ok. But how do I create an instance of DeviceManager with the configured dependency and passing along an integer of my choice in composition root?
I thought about creating a factory.
public class DeviceManagerFactory : IDeviceManagerFactory
{
private readonly Container _container;
public DeviceManagerFactory(Container container)
{
_container = container;
}
public DeviceManager Create(int minutes)
{
var configRepo = _container.GetInstance<IDeviceConfigurationRepository>();
return new DeviceManager(configRepo, minutes);
}
}
This is pretty simple.
However now I do not have a registration for DeviceManager which is the type I ultimately need. Should I change these dependencies to the factory instead?
public class ExampleClassUsingDeviceManager
{
private readonly DeviceManager _deviceManager;
public ExampleClassUsingDeviceManager(DeviceManager deviceManager, ...)
{
_deviceManage = deviceManager;
}
// actions...
}
For this to work and to avoid circular dependencies I would probably have to move the factory from the "application" project (as opposed to class libraries) where the composition root is to the project where the DeviceManager is implemented.
Is that OK? It would of course mean passing around the container.
Any other solutions to this?
EDIT
In the same project for other types I am using parameter objects to inject configuration into my object graph. This works OK since I only have one class instance per parameter object type. If I had to inject different parameter object instances (for example MongoDbRepositoryOptions) into different class instances (for example MongoDbRepository) I would have to use some kind of named registration - which SimpleInjector doesn't support. Even though I only have one integer the parameter object pattern would solve my problem. But I'm not too happy about this pattern knowing it will break as soon as I have multiple instances of the consuming class (i.e. MongoDbRepository).
Example:
MongoDbRepositoryOptions options = new MongoDbRepositoryOptions();
MongoDbRepositoryOptions.CollectionName = "config";
MongoDbRepositoryOptions.ConnectionString = "mongodb://localhost:27017";
MongoDbRepositoryOptions.DatabaseName = "dev";
container.RegisterSingleton<MongoDbRepositoryOptions>(options);
container.RegisterSingleton<IDeviceConfigurationRepository, MongoDbRepository>();
I am excited to hear how you deal best with configurations done at composition root.
Letting your DeviceManagerFactory depend on Container is okay, as long as that factory implementation is part of your Composition Root.
Another option is to inject the IDeviceConfigRepository into the DeviceManagerFactory, this way you can construct a DeviceManager without the need to access the container:
public class DeviceManagerFactory : IDeviceManagerFactory {
private readonly IDeviceConfigurationRepository _repository;
public DeviceManagerFactory(IDeviceConfigurationRepository repository) {
_repository = repository;
}
public DeviceManager Create(int minutes) {
return new DeviceManager(_repository, minutes);
}
}
However now I do not have a registration for DeviceManager which is the type I ultimately need. Should I change these dependencies to the factory instead?
In general I would say that factories are usually the wrong abstraction, since they complicate the consumer instead of simplifying them. So you should typically depend on the service abstraction itself (instead of depending on a factory abstraction that can produces service abstraction implementations), or you should inject some sort of proxy or mediator that completely hides the existence of the service abstraction from point of view of the consumer.
#DavidL points at my blog post about runtime data. I'm unsure though whether the cacheTimeout is runtime data, although you seem to be using it as such, since you are passing it in into the Create method of the factory. But we're missing some context here, to determine what's going on. My blog post still stands though, if it is runtime data, it's an anti-pattern and in that case you should
pass runtime data through method calls of the API
or
retrieve runtime data from specific abstractions that allow resolving runtime data.
UPDATE
In case the value you are using is an application constant, that is read through the configuration file, and doesn't change during lifetime of the application, it is perfectly fine to inject it through the constructor. In that case it is not a runtime value. There is also no need for a factory.
There are multiple ways to register this in Simple Injector, for instance you can use a delegate to register the DeviceManager class:
container.Register<DeviceManager>(() => new DeviceManager(
container.GetInstance<IDeviceConfigRepository>(),
cacheTimeout: 15));
Downside of this approach is that you lose the ability of Simple Injector to auto-wire the type for you, and you disable Simple Injector's ability to verify, diagnose and visualize the object graph for you. Sometimes this is fine, while other times it is not.
The problem here is that Simple Injector blocks the registration of primitive types (because they cause ambiguity) while not presenting you with a clean way to make the registration. We are considering (finally) adding such feature in v4, but that doesn't really address your current needs.
Simple Injector doesn't easily allow you to specify a primitive dependency, while letting the container auto-wire the rest. Simple Injector's IDependencyInjectionBehavior abstraction allows you to override the default behavior (which is to disallow doing this). This is described here, but I usually advice against doing this, because it is usually requires quite a lot of code.
There are basically two options here:
Abstract the specific logic that deals with this caching out of the class and wrap it in a new class. This class will have just the cacheTimeout as its dependency. This is of course only useful when there actually is logical to abstract and is usually only logical when you are injecting that primitive value into multiple consumers. For instance, instead of injecting a connectionstring into multiple classes, you're probably better of injecting an IConnectionFactory into those classes instead.
Wrap the cacheTimeout value into a complex data container specific for the consuming class. This enables you to register that type, since it resolves the ambiguity issue. In fact, this is what you yourself are already suggesting and I think this is a really good thing to do. Since those values are constant at runtime, it is fine to register that DTO as singleton, but make sure to make it immutable. When you give each consumer its own data object, you won't have to register multiple instances of those, since they are unique. Btw, although named registations aren't supported, you can make conditional or contextual registrations using RegisterConditional and there are other ways to achieve named registrations with Simple Injector, but again, I don't think you really need that here.
I've been using Dependency Injection for a while, and now I want to give a talk about IoC and DI to a group of new developers. I remember explaining it to one guy personally and he asked me:
"Why not just use:
private IMyInterface _instance = new MyImplementaion();
instead of going through all the DI trouble. "
My answer was: "Unit testing requires mocks and stubs." - but we do not write unit tests in my company so it did not convince him. I told him that concrete implementation is bad since you are tightly coupled to one implementation. Changing one component will cause change in another.
Can you give an example for such code?
Can you give me more reasons why this code is bad?
It seem so obvious to me that I have trouble explaining it :-)
The problem with the following coupling
public class MyClass
{
private IMyInterface _instance = new MyImplementation();
...
Means that any time MyClass is created (whether directly, or by an IoC container) is that it will always immediately create a concrete MyImplementation and bind its dependency _instance to this concrete implementation. In turn, it is likely that MyImplementation has other dependencies, which are also coupled this way.
Benefits of decoupling of classes such that MyClass is only dependent on interfaces to its dependencies, and not concrete implementations of the dependencies (i.e. the D of SOLID principles) include:
for Unit Testing - As you've mentioned, in order to test MyClass in isolation, with new'ed dependencies, you would need to resort to nasty things like Moles / Fakes in order to mock out the the hard wired MyImplementation dependency.
for Substitution - by coupling only to an interface, you can now swap out different concrete implementations of IMyInterface (e.g. via configuring your IoC bootstrapping) without changing any code in MyClass.
for making dependencies explicit and obvious in your system, as the IMyInterface dependency may have further dependencies, which need to be resolved (and may need configuration considerations as well). If MyClass hides the IMyInterface dependency internally, it is not visible to the caller as to what the dependencies of MyClass are. Although in classic 1990's OO this was commonplace (i.e. encapsulation + composition), this can obscure the implementation as deployment of all dependencies still needs to be done. However, with coupling done on interface level (i.e. consumers of MyClass will do so only via IMyClass), the coupling-visible interface is IMyClass which will again hide the dependency on IMyInterface, since constructors are not visible on the interface).
for configurable dependency lifespan control. By injecting IMyInterface, instead of newing MyImplementation, you are allowing additional configuration options with respect to the lifespan management of the MyImplementation object. When the original hardwired creation of MyImplementation was done on MyClass, it was effectively taking ownership of MyImplementation's lifespan with a 1:1 relationship between the two class instances. By leaving this to the IoC container, you can now play with other options of MyImplementation's lifespan, which might be more efficient, e.g. if MyImplementation instances are thread-safe, you may elect to share an instance across multiple instances of MyClass, for instance.
In summary, here's how I believe the refactoring should look suitable for IoC constructor dependency injection:
public class MyClass
{
// Coupled onto the the interface. Dependency can be mocked, and substituted
private readonly IMyInterface _instance;
public MyClass(IMyInterface instance)
{
_instance = instance;
}
...
The IoC container bootstrapping will define WHICH implementation of IMyInterface needs to be bound, and will also define the lifespan of the dependency, e.g. in Ninject:
Bind<IMyInterface>()
.To<SomeConcreteDependency>() // Which implements IMyInterface
.InSingletonScope();
I most commonly am tempted to use "bastard injection" in a few cases. When I have a "proper" dependency-injection constructor:
public class ThingMaker {
...
public ThingMaker(IThingSource source){
_source = source;
}
But then, for classes I am intending as public APIs (classes that other development teams will consume), I can never find a better option than to write a default "bastard" constructor with the most-likely needed dependency:
public ThingMaker() : this(new DefaultThingSource()) {}
...
}
The obvious drawback here is that this creates a static dependency on DefaultThingSource; ideally, there would be no such dependency, and the consumer would always inject whatever IThingSource they wanted. However, this is too hard to use; consumers want to new up a ThingMaker and get to work making Things, then months later inject something else when the need arises. This leaves just a few options in my opinion:
Omit the bastard constructor; force the consumer of ThingMaker to understand IThingSource, understand how ThingMaker interacts with IThingSource, find or write a concrete class, and then inject an instance in their constructor call.
Omit the bastard constructor and provide a separate factory, container, or other bootstrapping class/method; somehow make the consumer understand that they don't need to write their own IThingSource; force the consumer of ThingMaker to find and understand the factory or bootstrapper and use it.
Keep the bastard constructor, enabling the consumer to "new up" an object and run with it, and coping with the optional static dependency on DefaultThingSource.
Boy, #3 sure seems attractive. Is there another, better option? #1 or #2 just don't seem worth it.
As far as I understand, this question relates to how to expose a loosely coupled API with some appropriate defaults. In this case, you may have a good Local Default, in which case the dependency can be regarded as optional. One way to deal with optional dependencies is to use Property Injection instead of Constructor Injection - in fact, this is sort of the poster scenario for Property Injection.
However, the real danger of Bastard Injection is when the default is a Foreign Default, because that would mean that the default constructor drags along an undesirable coupling to the assembly implementing the default. As I understand this question, however, the intended default would originate in the same assembly, in which case I don't see any particular danger.
In any case you might also consider a Facade as described in one of my earlier answers: Dependency Inject (DI) "friendly" library
BTW, the terminology used here is based on the pattern language from my book.
My trade-off is a spin on #BrokenGlass:
1) Sole constructor is parameterized constructor
2) Use factory method to create a ThingMaker and pass in that default source.
public class ThingMaker {
public ThingMaker(IThingSource source){
_source = source;
}
public static ThingMaker CreateDefault() {
return new ThingMaker(new DefaultThingSource());
}
}
Obviously this doesn't eliminate your dependency, but it does make it clearer to me that this object has dependencies that a caller can deep dive into if they care to. You can make that factory method even more explicit if you like (CreateThingMakerWithDefaultThingSource) if that helps with understanding. I prefer this to overriding the IThingSource factory method since it continues to favor composition. You can also add a new factory method when the DefaultThingSource is obsoleted and have a clear way to find all the code using the DefaultThingSource and mark it to be upgraded.
You covered the possibilities in your question. Factory class elsewhere for convenience or some convenience within the class itself. The only other unattractive option would be reflection-based, hiding the dependency even further.
One alternative is to have a factory method CreateThingSource() in your ThingMaker class that creates the dependency for you.
For testing or if you do need another type of IThingSource you would then have to create a subclass of ThingMaker and override CreateThingSource() to return the concrete type you want. Obviously this approach only is worth it if you mainly need to be able to inject the dependency in for testing, but for most/all other purposes do not need another IThingSource
I vote for #3. You'll be making your life--and the lives of other developers--easier.
If you have to have a "default" dependency, also known as Poor Man’s Dependency Injection, then you have to initialize and "wire" the dependency somewhere.
I will keep the two constructors but have a factory just for the initialization.
public class ThingMaker
{
private IThingSource _source;
public ThingMaker(IThingSource source)
{
_source = source;
}
public ThingMaker() : this(ThingFactory.Current.CreateThingSource())
{
}
}
Now in the factory create the default instance and allow the method to be overrided:
public class ThingFactory
{
public virtual IThingSource CreateThingSource()
{
return new DefaultThingSource();
}
}
Update:
Why using two constructors:
Two constructors clearly show how the class is intended to be used. The parameter-less constructor states: just create an instance and the class will perform all of it's responsibilities. Now the second constructor states that the class depends of IThingSource and provides a way of using an implementation different than the default one.
Why using a factory:
1- Discipline: Creating new instances shouldn't be part of the responsibilities of this class, a factory class is more appropriate.
2- DRY: Imagine that in the same API other classes also depend on IThingSource and do the same. Override once the factory method returning IThingSource and all the classes in your API automatically start using the new instance.
I don't see a problem in coupling ThingMaker to a default implementation of IThingSource as long as this implementation makes sense to the API as a whole and also you provide ways to override this dependency for testing and extension purposes.
You are unhappy with the OO impurity of this dependency, but you don't really say what trouble it ultimately causes.
Is ThingMaker using DefaultThingSource in any way that does not conform to IThingSource? No.
Could there come a time where you would be forced to retire the parameterless constructor? Since you are able to provide a default implementation at this time, unlikely.
I think the biggest problem here is the choice of name, not whether to use the technique.
The examples usually related to this style of injection are often extremely simplisitic: "in the default constructor for class B, call an overloaded constructor with new A() and be on your way!"
The reality is that dependencies are often extremely complex to construct. For example, what if B needs a non-class dependency like a database connection or application setting? You then tie class B to the System.Configuration namespace, increasing its complexity and coupling while lowering its coherence, all to encode details which could simply be externalized by omitting the default constructor.
This style of injection communicates to the reader that you have recognized the benefits of decoupled design but are unwilling to commit to it. We all know that when someone sees that juicy, easy, low-friction default constructor, they are going to call it no matter how rigid it makes their program from that point on. They can't understand the structure of their program without reading the source code for that default constructor, which isn't an option when you just distribute the assemblies. You can document the conventions of connection string name and app settings key, but at that point the code doesn't stand on its own and you put the onus on the developer to hunt down the right incantation.
Optimizing code so those who write it can get by without understanding what they are saying is a siren song, an anti-pattern that ultimately leads to more time lost in unraveling the magic than time saved in initial effort. Either decouple or don't; keeping a foot in each pattern diminishes the focus of both.
For what it is worth, all the standard code I've seen in Java does it like this:
public class ThingMaker {
private IThingSource iThingSource;
public ThingMaker() {
iThingSource = createIThingSource();
}
public virtual IThingSource createIThingSource() {
return new DefaultThingSource();
}
}
Anybody who doesn't want a DefaultThingSource object can override createIThingSource. (If possible, the call to createIThingSource would be somewhere other than the constructor.) C# does not encourage overriding like Java does, and it might not be as obvious as it would be in Java that the users can and perhaps should provide their own IThingSource implementation. (Nor as obvious how to provide it.) My guess is that #3 is the way to go, but I thought I would mention this.
Just an idea - perhaps a bit more elegant but sadly doesn't get rid of the dependency:
remove the "bastard constructor"
in the standard constructor you make the source param default to null
then you check for source being null and if this is the case you assign it "new DefaultThingSource()" otherweise whatever the consumer injects
Have an internal factory (internal to your library) that maps the DefaultThingSource to IThingSource, which is called from the default constructor.
This allows you to "new up" the ThingMaker class without parameters or any knowledge of IThingSource and without a direct dependency on DefaultThingSource.
For truly public APIs, I generally handle this using a two-part approach:
Create a helper within the API to allow an API consumer to register "default" interface implementations from the API with their IoC container of choice.
If it is desirable to allow the API consumer to use the API without their own IoC container, host an optional container within the API that is populated the same "default" implementations.
The really tricky part here is deciding when to activate the container #2, and the best choice approach will depend heavily on your intended API consumers.
I support option #1, with one extension: make DefaultThingSource a public class. Your wording above implies that DefaultThingSource will be hidden from public consumers of the API, but as I understand your situation there's no reason not to expose the default. Furthermore, you can easily document the fact that outside of special circumstances, a new DefaultThingSource() can always be passed to the ThingMaker.
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.