Unity Container - multiple databases with generic unity of work - c#

I am using generic unity of work for EF6 from here:
https://genericunitofworkandrepositories.codeplex.com/
I have an application which uses two databases. I've created additional UnitOfWork interface and class that implements original unit of work interface:
namespace Repository.Pattern.UnitOfWork
{
public interface ILotteryBackOfficeUnitOfWorkAsync : IUnitOfWorkAsync
{
}
}
Second unit of work type for second database initialization:
namespace Repository.Pattern.Ef6
{
public class LotteryBackOfficeUnitOfWork : UnitOfWork, ILotteryBackOfficeUnitOfWorkAsync
{
public LotteryBackOfficeUnitOfWork(IDataContextAsync dataContext)
: base(dataContext)
{ }
}
}
In unity I register both unit of works for different data contexts:
public static void RegisterTypes(IUnityContainer container)
{
// NOTE: To load from web.config uncomment the line below. Make sure to add a Microsoft.Practices.Unity.Configuration to the using statements.
// container.LoadConfiguration();
// TODO: Register your types here
// container.RegisterType<IProductRepository, ProductRepository>();
var purusLotteryConnectionString = WebConfigurationManager.ConnectionStrings["PurusLotteryContext"].ConnectionString;
var purusLotteryBackOfficeConnectionString = WebConfigurationManager.ConnectionStrings["PurusLotteryBackOfficeContext"].ConnectionString;
container.RegisterType<IDataContextAsync, PurusLotteryContext>(new InjectionConstructor(purusLotteryConnectionString));
container.RegisterType<IUnitOfWorkAsync, UnitOfWork>(new HierarchicalLifetimeManager());
container.RegisterType<IDataContextAsync, PurusLotteryBackOfficeContext>("LotteryBackOfficeContext", new InjectionConstructor(purusLotteryBackOfficeConnectionString));
container.RegisterType<ILotteryBackOfficeUnitOfWorkAsync, LotteryBackOfficeUnitOfWork>(new HierarchicalLifetimeManager(),
new InjectionConstructor(container.Resolve<IDataContextAsync>("LotteryBackOfficeContext")));
container.RegisterType<IHomeService, HomeService>();
}
It works, but is this correct procedure?

One error I see is that you resolve during the registration phase. Not only is this dangerous (as is explained in the documentation of a different DI libary), in your case it causes the PurusLotteryBackOfficeContext to be used as constant and therefore injected as Singleton into the LotteryBackOfficeUnitOfWork. In other words, while this might seem to work during development, this will not work, because a DbContext can't be used as singleton.
Instead, you should use Unity's auto-wiring abilities as much as you can, otherwise a DI library has no advantage (and only disadvantages) over building up object graphs by hand.
Besides this, you are violating the Liskov Substitution Principle (LSP) in your design and this is causing you trouble in your DI configuration. You are violating the LSP because you have two incompatible implementations of the same abstraction. Both PurusLotteryContext and PurusLotteryBackOfficeContext implement IDataContextAsync, but they are incompatible, because they can't be interchanged, because they both work on a completely different database schema. Although they might seem to share the same interface, they don't share the same contract. Just look what happens when you inject a PurusLotteryContext into some class that needs to work with the backoffice. The application will break and this means you are violating the LSP.
Solution is to give them both their own independent abstraction. At first this might seem a weird thing to do, because they both have the same methods. But remember that an interface is much more than a set of method signatures; an interface describes a contract and behavior and since both implementations work on a completely different database schema they have a completely different contract. When you separate this, your code would look like this:
public class PurusLotteryContext : IPurusLotteryDataContextAsync {
public PurusLotteryContext(string conString) : base(conString) { }
}
public class LotteryUnitOfWork : ILotteryUnitOfWorkAsync {
public LotteryUnitOfWork(IPurusLotteryDataContextAsync dc) { }
}
public class PurusLotteryBackOfficeContext : IPurusLotteryBackOfficeDataContextAsync {
public PurusLotteryBackOfficeContext(string conString) : base(conString) { }
}
public class LotteryBackOfficeUnitOfWork : ILotteryBackOfficeUnitOfWorkAsync {
public LotteryBackOfficeUnitOfWork(IPurusLotteryBackOfficeDataContextAsync dc) { }
}
And this allows you to have the following registration:
container.Register<IPurusLotteryDataContextAsync>(new HierarchicalLifetimeManager(),
new InjectionFactory(c => new PurusLotteryContext(purusLotteryConnectionString)));
container.Register<IPurusLotteryBackOfficeDataContextAsync>(
new HierarchicalLifetimeManager(),
new InjectionFactory(c => new PurusLotteryBackOfficeContext(
purusLotteryBackOfficeConnectionString)));
container.RegisterType<ILotteryUnitOfWorkAsync, LotteryUnitOfWork>(
new HierarchicalLifetimeManager());
container.RegisterType<ILotteryBackOfficeUnitOfWorkAsync, LotteryBackOfficeUnitOfWork>(
new HierarchicalLifetimeManager());
Notice a few things about this registration:
The data context implementations are registered as hierarchical, because you typically want the Entity Framework DbContext to have a 'per request' lifestyle.
The data context implementations are registered using a factory, compared to using the container's auto-wiring ability. This is because auto-wiring doesn't help for these classes and a factory delegate will not only make the registration simpler, because also more type-safe (the compiler will help us if we make an error).

I know my answer comes late, but I want to point to a different direction here instead #Steve suggestion.
What about the named registration? Using a name to register the same interface with different implementations. Make sense that you have a contract and different implementations, there is nothing wrong on that.
If you want to keep the same interface at the time you register both implementations you can do it with a different name, take a look on the answer below
https://stackoverflow.com/a/18665983
Now, the intent for LSP is that derived types must be completely substitutable for their base types and again, in your case doesn't make to create a new contract with the same functionality and different signatures. I disagree with the #Steve suggestion. Bellow I am attaching a great example of LSP
https://stackoverflow.com/a/584732/819153
Another point of interest is the UnitOfWork.
When you're using EntityFramework and you instantiate your DbContext -
you're creating a new UnitOfWork.With EntityFramework you can "flush and reset" the UnitofWork by using SaveChanges(), you don't need to SaveChanges just to return the new ID - EF does it in the scope of the transaction already!
Here is a good article that you can read about it.
http://rob.conery.io/2014/03/04/repositories-and-unitofwork-are-not-a-good-idea/
I would recommend injecting directly the DataContext instead of the IUnitOfWork
Hope this help

Related

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

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

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

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

Dependency injection with factory for child class with constructor argument

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

Benefit of IoC over my Factory Singleton

There seems to be a stigma on SO regarding use of Singletons. I've never personally bought into it but for the sake of open mindedness I'm attempting to give IoC concepts a try as an alternative because I'm frankly bored with my everyday work and would like to try something different. Forgive me if my interpretation of IoC concepts are incorrect or misguided.
Here's the situation: I'm building a simple HttpListener based web server in a windows service that utilizes a plug-in model to determine how a request should be handled based on the URL requested (just like everyone else that asks about HttpListener). My approach to discovering the plug-ins is to query a configured directory for assemblies decorated with a HttpModuleAssemblyAttribute. These assemblies can contain 0 or more IHttpModule children who in addition are decorated with a HttpModuleAttribute used to specify the module's name, version, human readable description and various other information. Something like:
[HttpModule(/*Some property values that matter */)]
public class SimpleHttpModule : IHttpModule
{
public void Execute(HttpListenerContext context)
{
/* Do Something Special */
}
}
When an HttpModule is discovered I would typically add it to a Dictionary<string, Type> object who's sole purpose is to keep track of which modules we know about. This dictionary would typically live in my variety of a Singleton which takes on the persona of an ACE style Singleton (a legacy from my C++ days where I learned about Singletons).
Now what I am trying to implement is something similar using (my understanding of) general IoC concepts. Basically what I have is an AppService collection where IAppService is defined as:
public interface IAppService : IDisposable
{
void Initialize();
}
And my plug-in AppService would look something like:
[AppService("Plugins")]
internal class PluginAppService : IAppService, IDictionary<string, Type>
{
/* Common IDictionary Implementation consisting of something like: */
internal Type Item(string modName)
{
Type modType;
if (!this.TryGetValue(modName, out modType)
return null;
return modType;
}
internal void Initialize()
{
// Find internal and external plug-ins and add them to myself
}
// IDisposable clean up method that attempts to dispose all known plug-ins
}
Then during service OnStart I instantiate an instance of AppServices which is locally known but passed to the constructor of all instantiated plug-ins:
public class AppServices : IDisposable, IDictionary<string, IAppService>
{
/* Simple implementation of IDictionary */
public void Initialization()
{
// Find internal IAppService implementations, instantiate them (passing this as a constructor parameter), initialize them and add them to this.
// Somewhere in there would be something like
Add(appSvcName, appSvc);
}
}
Our once single method implementation becomes an abstract implementation + a constructor on the child:
[HttpModule(/*Some property values that matter */)]
public abstract class HttpModule : IHttpModule
{
protected AppServices appServices = null;
public HttpModule(AppServices services)
{
appServices = services;
}
public abstract void Execute(HttpListenerContext context);
}
[HttpModule(/*Some property values that matter */)]
public class SimpleHttpModule : HttpModule
{
public SimpleHttpModule(AppServices services) : base(services) { }
public override void Execute(HttpListenerContext context)
{
/* Do Something Special */
}
}
And any access to commonly used application services becomes:
var plugType = appServices["Plugins"][plugName];
rather than:
var plugType = PluginManager.Instance[plugName];
Am I missing some basic IoC concept here that would simplify this all or is there really a benefit to all of this additional code? In my world, Singletons are simple creatures that allow code throughout a program to access needed (relatively static) information (in this case types).
To pose the questions more explicitly:
Is this a valid implementation of a Factory Singleton translated to IoC/DI concepts?
If it is, where is the payback/benefit for the additional code required and imposition of a seemingly more clunky API?
IoC is a generic term. Dependency Injection is the more preferred term these days.
Dependency Injection really shines in several circumstances. First, it defines a more testable architecture than solutions that have hard-coded instantiations of dependencies. Singletons are difficult to unit test because they are static, and static data cannot be "unloaded".
Second, Dependency Injection not only instantiates the type you want, but all dependant types. Thus, if class A needs class B, and class B needs class C and D, then a good DI framework will automatically create all dependencies, and control their lifetimes (for instance, making them live for the lifetime of a single web request).
DI Containers can be though of as generic factories that can instantiate any kind of object (so long as it's properly configured and meets the requirments of the DI framework). So you don't have to write a custom factory.
Like with any generic solution, it's designed to give 90% of the use cases what they need. Sure, you could create a hand crafted custom linked list data structure every time you need a collection, but 90=% of the time a generic one will work just fine. The same is true of DI and Custom Factories.
IoC becomes more interesting when you get round to writing unit tests. Sorry to answer a question with more questions, but... What would the unit tests look like for both of your implementations? Would you be able to unit test classes that used the PluginManager without looking up assemblies from disk?
EDIT
Just because you can achieve the same functionality with singletons doesn't mean it's as easy to maintain. By using IoC (at least this style with constructors) you're explicitly stating the dependencies an object has. By using singletons that information is hidden within the class. It also makes it harder to replace those dependencies with alternate implementations.
So, with a singleton PluginManager it would difficult to test your HTTP server with mock plugins, rather it looking them up from some location on disk. With the IoC version, you could pass around an alternate version of the IAppService that just looks the plugins up from a pre-populated Dictionary.
While I'm still not really convinced that IoC/DI is better in this situation, I definitely have seen benefit as the project's scope crept. For things like logging and configurability it most certainly is the right approach.
I look forward to experimenting with it more in future projects.

Having trouble understanding ninject (or just IOC container in general) over factory DI?

Okay, so recently I've been reading into ninject but I am having trouble understanding what makes it better over why they referred do as 'poor man's' DI on the wiki page. The sad thing is I went over all their pages on the wiki and still don't get it =(.
Typically I will wrap my service classes in a factory pattern that handles the DI like so:
public static class SomeTypeServiceFactory
{
public static SomeTypeService GetService()
{
SomeTypeRepository someTypeRepository = new SomeTypeRepository();
return = new SomeTypeService(someTypeRepository);
}
}
Which to me seems a lot like the modules:
public class WarriorModule : NinjectModule {
public override void Load() {
Bind<IWeapon>().To<Sword>();
Bind<Samurai>().ToSelf().InSingletonScope();
}
}
Where each class would have it's associated module and you Bind it's constructor to a concrete implementation. While the ninject code is 1 less line I am just not seeing the advantage, anytime you add/remove constructors or change the implementation of an interface constructor, you'd have to change the module pretty much the same way as you would in the factory no? So not seeing the advantage here.
Then I thought I could come up with a generic convention based factory like so:
public static TServiceClass GetService<TServiceClass>()
where TServiceClass : class
{
TServiceClass serviceClass = null;
string repositoryName = typeof(TServiceClass).ToString().Replace("Service", "Repository");
Type repositoryType = Type.GetType(repositoryName);
if (repositoryType != null)
{
object repository = Activator.CreateInstance(repositoryType);
serviceClass = (TServiceClass)Activator.CreateInstance(typeof (TServiceClass), new[]{repository});
}
return serviceClass;
}
However, this is crappy for 2 reasons: 1) Its tightly dependent on the naming convention, 2) It assumed the repository will never have any constructors (not true) and the service's only constructor will be it's corresponding repo (also not true). I was told "hey this is where you should use an IoC container, it would be great here!" And thus my research began...but I am just not seeing it and am having trouble understanding it...
Is there some way ninject can automatically resolve constructors of a class without a specific declaration such that it would be great to use in my generic factory (I also realize I could just do this manually using reflection but that's a performance hit and ninject says right on their page they don't use reflection).
Enlightment on this issue and/or showing how it could be used in my generic factory would be much appreciated!
EDIT: Answer
So thanks to the explanation below I was ably to fully understand the awesomeness of ninject and my generic factory looks like this:
public static class EntityServiceFactory
{
public static TServiceClass GetService<TServiceClass>()
where TServiceClass : class
{
IKernel kernel = new StandardKernel();
return kernel.Get<TServiceClass>();
}
}
Pretty awesome. Everything is handled automatically since concrete classes have implicit binding.
The benefit of IoC containers grows with the size of the project. For small projects their benefit compared to "Poor Man's DI" like your factory is minimal. Imagine a large project which has thousands of classes and some services are used in many classes. In this case you only have to say once how these services are resolved. In a factory you have to do it again and again for every class.
Example: If you have a service MyService : IMyService and a class A that requires IMyService you have to tell Ninject how it shall resolve these types like in your factory. Here the benefit is minimal. But as soon as you project grows and you add a class B which also depends on IMyService you just have to tell Ninject how to resolve B. Ninject knows already how to get the IMyService. In the factory on the other hand you have to define again how B gets its IMyService.
To take it one step further. You shouldn't define bindings one by one in most cases. Instead use convention based configuration (Ninject.Extension.Conventions). With this you can group classes together (Services, Repositories, Controllers, Presenters, Views, ....) and configure them in the same way. E.g. tell Ninject that all classes which end with Service shall be singletons and publish all their interfaces. That way you have one single configuration and no change is required when you add another service.
Also IoC containers aren't just factories. There is much more. E.g. Lifecycle managment, Interception, ....
kernel.Bind(
x => x.FromThisAssembly()
.SelectAllClasses()
.InNamespace("Services")
.BindToAllInterfaces()
.Configure(b => b.InSingletonScope()));
kernel.Bind(
x => x.FromThisAssembly()
.SelectAllClasses()
.InNamespace("Repositories")
.BindToAllInterfaces());
To be fully analagous your factory code should read:
public static class SomeTypeServiceFactory
{
public static ISomeTypeService GetService()
{
SomeTypeRepository someTypeRepository = new SomeTypeRepository();
// Somewhere in here I need to figure out if i'm in testing mode
// and i have to do this in a scope which is not in the setup of my
// unit tests
return new SomeTypeService(someTypeRepository);
}
private static ISomeTypeService GetServiceForTesting()
{
SomeTypeRepository someTypeRepository = new SomeTypeRepository();
return new SomeTestingTypeService(someTypeRepository);
}
}
And the equilvalent in Ninject would be:
public class WarriorModule : NinjectModule {
public override void Load() {
Bind<ISomeTypeService>().To<SomeTypeService>();
}
}
public class TestingWarriorModule : NinjectModule {
public override void Load() {
Bind<ISomeTypeService>().To<SomeTestingTypeService>();
}
}
Here, you can define the dependencies declaratively, ensuring that the only differences between your testing and production code are contained to the setup phase.
The advantage of an IoC is not that you don't have to change the module each time the interface or constructor changes, it's the fact that you can declare the dependencies declaratively and that you can plug and play different modules for different purposes.

Categories