Simple Dependency Resolver - c#

How do you create simple Dependency Resolver, with out using any built in or library such as Autofac, Ninject, etc.
This was my interview question.
I wrote this simple code and they said it does not look good. Its like very hard coded idea.
public interface IRepository { }
interface IDataProvider
{
List<string> GetData();
}
public class SQLDataProvider : IDataProvider
{
private readonly IRepository _repository { get; set; }
public SQLDataProvider(IRepository repository)
{
_repository = repository;
}
public List<string> GetData()
{
return new List<string> { "" };
}
}
public class MockDataProvider : IDataProvider
{
public List<string> GetData()
{
return new List<string> { "" };
}
}
class Program
{
static void Main(string[] args)
{
string targetClass = "SQLDataProvider";
//Here i need to supply IRepository instance too
IDataProvider dataProvider =
(IDataProvider)Activator.CreateInstance(typeof(IDataProvider), targetClass);
}
}
What better code i do and supply other object instance for constructor parameter?

DI Containers are complex libraries. Building them takes years and maintaining them decades. But to demonstrate their working, you can write a simplistic implementations in just a few lines of code.
At its core a DI Container would typically wrap a dictionary with System.Type as its key and, the value would be some object that allows you to create new instances of that type. When you write a simplistic implementation System.Func<object> would do. Here is an example that contains several Register methods, both a generic and non-generic GetInstance method and allows Auto-Wiring:
public class Container
{
private readonly Dictionary<Type, Func<object>> regs = new();
public void Register<TService, TImpl>() where TImpl : TService =>
regs.Add(typeof(TService), () => this.GetInstance(typeof(TImpl)));
public void Register<TService>(Func<TService> factory) =>
regs.Add(typeof(TService), () => factory());
public void RegisterInstance<TService>(TService instance) =>
regs.Add(typeof(TService), () => instance);
public void RegisterSingleton<TService>(Func<TService> factory)
{
var lazy = new Lazy<TService>(factory);
Register(() => lazy.Value);
}
public object GetInstance(Type type)
{
if (regs.TryGetValue(type, out Func<object> fac)) return fac();
else if (!type.IsAbstract) return this.CreateInstance(type);
throw new InvalidOperationException("No registration for " + type);
}
private object CreateInstance(Type implementationType)
{
var ctor = implementationType.GetConstructors().Single();
var paramTypes = ctor.GetParameters().Select(p => p.ParameterType);
var dependencies = paramTypes.Select(GetInstance).ToArray();
return Activator.CreateInstance(implementationType, dependencies);
}
}
You can use it as follows:
var container = new Container();
container.RegisterInstance<ILogger>(new FileLogger("c:\\logs\\log.txt"));
// SqlUserRepository depends on ILogger
container.Register<IUserRepository, SqlUserRepository>();
// HomeController depends on IUserRepository
// Concrete instances don't need to be resolved
container.GetInstance(typeof(HomeController));
WARNING: You should never use such naive and simplistic implementation as given above. It lacks many important features that mature DI libraries give you, yet gives no advantage over using Pure DI (i.e. hand wiring object graphs). You lose compile-time support, without getting anything back.
When your application is small, you should start with Pure DI and once your application and your DI configuration grow to the point that maintaining you Composition Root becomes cumbersome, you could consider switching to one of the established DI libraries.
Here are some of the features that this naive implementation lacks compared to the established libraries:
Auto-Registration: The ability to apply Convention over Configuration by registering a set of types with in single line, instead of having to register each type manually.
Interception: the ability to apply decorators or interceptors for a range of types
Generics: Mapping open-generic abstractions to open generic implementations
Integration: using the library with common application platforms (such as ASP.NET MVC, Web API, .NET Core, etc)
Lifetime Management: The ability to registering types with custom lifestyles (e.g. Scoped or Per Request).
Error handling: Detection of misconfiguration such as cyclic dependencies. This simplistic implementation throws a stack overflow exception.
Verification: Features or tools for verifying the correctness of the configuration (to compensate the loss of compile-time support) and diagnosing common configuration mistakes.
Performance: Building large object graphs will be slow using this simplistic implementation (e.g. causes a lot of GC pressure due to the amount of produced garbage).
These features and abilities allow you to keep your DI configuration maintainable when using a DI Container.

It's already a few years old, but Ayende once wrote a blog post about this:
Building an IoC container in 15 lines of code
But this is only the very simplest possible implementation.
Ayende himself stated in his next post that the existing IoC containers can do much more stuff than just returning class instances - and this is where it gets complicated.
As "Trust me - I'm a Doctor" already said in his comment: implementing a complete IoC container is everything but trivial.

Related

Use the ActivatorUtilities to determine which implementation to inject at runtime

I am using the built in .Net Core IoC container to resolve the application's dependencies. The way I have configured it is as follows with the use of Scrutor to scan my assembly:
services.Scan(s => s
.FromAssembliesOf(currentAssemblyTypesList)
.AddClasses(false)
.UsingRegistrationStrategy(RegistrationStrategy.Append)
.AsImplementedInterfaces()
.WithTransientLifetime());
Up until now I've had simple cases in which each interface is implemented by one dependency so the previous configuration works perfectly to resolve the whole dependency tree.
Now consider the following code:
public interface IService {}
public class ServiceOne : IService
{
public ServiceOne(IDependency dependency) {}
}
public class ServiceTwo : IService
{
public ServiceTwo(IDependency dependency) {}
}
public class SomeClass
{
public SomeClass(IService service) {}
public void DoSomething()
{
this.service.SomeMethod();
}
}
In this case "SomeClass" is in the middle of a dependency tree and I have two services that implement the same interface and which one should be injected into "SomeClass" will not be known until runtime. For reasons unimportant I have been asked that I should use the ActivatorUtilities class for this.
I am dealing with two scenarios for determining which IService should be instantiated:
At application startup a flag gets set that determines which service is to be used before the registration takes place (for a similar setup but NOT for the same dependency tree).
During the execution of the "DoSomething" method a decision is made for which one of the two services should be used so I'm guessing some kind of factory should be registered and injected to "SomeClass".
So the question is what do I need to change or add to the dependency registration process and how do I use the ActivatorUtilities class to accomplish these objectives?
Thank you.
It is not very clear what you are trying to achieve but I think its something like this?
services.AddTransient<IService>(sp =>
{
if (condition1 && condition2)
ActivatorUtilities.CreateInstance<ServiceOne>(sp);
else
ActivatorUtilities.CreateInstance<ServiceTwo>(sp);
});
So the trickiest part was to figure out what to do with the first scenario when the registration has already taken place and it turns out that there is a way to replace a specific definition. This can be accomplished with the following code:
Func<IServiceProvider, object> factoryMethod = sp =>
{
if (condition1 && condition2)
{
return ActivatorUtilities.CreateInstance<ServiceOne>(sp);
}
else
{
return ActivatorUtilities.CreateInstance<ServiceTwo>(sp);
}
};
services.Replace(ServiceDescriptor.Describe(typeof(IService), factoryMethod, ServiceLifetime.Transient));
This works very nicely when condition1 and condition2 are known at the time of dependency registration, in other words at application startup before any request has been made.
For the other scenario in which the conditions are not known until the application is running and a request has been made, since the built in .Net Core IoC container is not as feature rich as others like Castle or Autofac one way of doing this is to manually create a factory method object, something like the following:
public interface IServiceFactory
{
IService Get(MyObject myObject);
}
public class ServiceFactory : IServiceFactory
{
private readonly IServiceProvider sp;
public ServiceFactory(IServiceProvider sp)
{
this.sp = sp;
}
public IService Get(MyObject myObject)
{
if(myObject.SomeProperty == "whatever")
{
return ActivatorUtilities.CreateInstance<ServiceOne>(this.sp);
}
else
{
return ActivatorUtilities.CreateInstance<ServiceTwo>(this.sp);
}
}
}
The only thing to keep in mind here is that the interface can and should be defined wherever all of the rest of the applications interfaces are defined, and you DO NOT want the rest of your application to be tightly coupled to the MicrosoftExtensions.DependencyInjection package because of the use of the IServiceProvider interface so the implementation of the factory should be wherever the rest of the registration logic is defined.
I looked really hard for an example of ActivatorUtilities.CreateFactory method that would give me something like this but was unable to find one. I hope this is useful for someone.

How to resolve circular dependencies inside of the service layer [duplicate]

This question already has answers here:
Dependency Injection Architectural Design - Service classes circular references
(4 answers)
Closed 3 years ago.
I know that others already had this very same issue, but I cannot find any statisfying solution, so I'm asking here for other ideas.
My business logic is contained in a service layer like that:
public class RoomService : IRoomService
{
private readonly IRoomRepository _roomRepository;
private readonly ICourseService _courseService;
public RoomService(IRoomRepository roomRepository, ICourseService courseService)
{
_roomRepository = roomRepository ?? throw new ArgumentNullException(nameof(roomRepository));
_courseService = courseService ?? throw new ArgumentNullException(nameof(courseService));
}
public Task DeleteRoomAsync(string id)
{
// Check if there are any courses for this room (requires ICourseService)
// Delete room
}
}
public class CourseService : ICourseService
{
private readonly ICourseRepository _courseRepository;
private readonly IRoomService _roomService;
public CourseService(ICourseRepository courseRepository, IRoomService roomService)
{
_courseRepository = courseRepository ?? throw new ArgumentNullException(nameof(courseRepository));
_roomService = roomService ?? throw new ArgumentNullException(nameof(roomService));
}
public Task GetAllCoursesInBuilding(string buildingId)
{
// Query all rooms in building (requires IRoomService)
// Return all courses for these rooms
}
}
This is just an example. There might be workarounds to avoid that the services depend on each other in this case, but I had multiple other situations in the past, where there wasn't any clean workaround.
As you can see, these two services depend on each other and dependency injection will fail because of the circular dependency.
Now I can imagine two ways to resolve this:
Solution 1
I could resolve the service-dependencies inside of the service methods that require them instead of injecting the service dependencies into the service constructor:
public class RoomService : IRoomService
{
private readonly IRoomRepository _roomRepository;
private readonly IServiceProvider _serviceProvider;
public RoomService(IRoomRepository roomRepository, IServiceProvider serviceProvider)
{
_roomRepository = roomRepository ?? throw new ArgumentNullException(nameof(roomRepository));
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
}
public Task DeleteRoomAsync(string id)
{
ICourseService courseService = _serviceProvider.GetRequiredService<ICourseService>();
// Check if there are any courses for this room (requires ICourseService)
// Delete room
}
}
Problem: This makes unit testing harder because I need to inject a mocked IServiceProvider that is able to resolve my ICourseService into the class constructor. Also it's not very clear when writing the unit tests, which services are required by each service method because that's completely implementation dependant.
Solution 2
The service method could require that the ICourseService is passed in from the controller as a method parameter:
public Task DeleteRoomAsync(ICourseService courseService, string id)
{
// Check if there are any courses for this room (requires ICourseService)
// Delete room
}
Problem: Now my controller needs to know about an implementation detail of the service method: DeleteRoomAsync requires an ICourseService object to do it's work.
I think that's not very clean because the requirements of DeleteRoomAsync might change in future, but the method signature should not.
Can you think of any alternative, cleaner solutions?
If your framework supports it, you can provide your injected dependencies as a Lazy<T> which defers resolution and allows you to have circular dependencies.
Here's what those service classes might look like:
class FooService : IFooService
{
protected Lazy<IBarService> _bar;
public FooService(Lazy<IBarService> bar)
{
_bar = bar;
}
public void DoSomething(bool callOtherService)
{
Console.WriteLine("Hello world. I am Foo.");
if (callOtherService)
{
_bar.Value.DoSomethingElse(false);
}
}
}
class BarService : IBarService
{
protected Lazy<IFooService> _foo;
public BarService(Lazy<IFooService> foo)
{
_foo = foo;
}
public void DoSomethingElse(bool callOtherService)
{
Console.WriteLine("Hello world. I am Bar.");
if (callOtherService)
{
_foo.Value.DoSomething(false);
}
}
}
The code that registers them does not require modification (at least not with Autofac):
public static IContainer CompositionRoot()
{
var builder = new ContainerBuilder();
builder.RegisterType<FooService>().As<IFooService>().SingleInstance();
builder.RegisterType<BarService>().As<IBarService>().SingleInstance();
builder.RegisterType<Application>().SingleInstance();
return builder.Build();
}
See a working example on DotNetFiddle.
If your framework does not support lazy injection like this, you can probably do the exact same thing using a factory (or any other pattern that defers resolution).
See also this answer which helped me come up with this solution.
The best solution is to avoid circular dependencies, of course, but it you're truly stuck, you can work around the issue by using property injection and RegisterInstance<T>(T t) (or its equivalent, if you're not using Autofac).
For example, if you have a FooService class and a BarService class that depend on each other, you can do this:
public static IContainer CompositionRoot()
{
var foo = new FooService();
var bar = new BarService();
foo.Bar = bar;
bar.Foo = foo;
var builder = new ContainerBuilder();
builder.RegisterInstance<IFooService>( foo );
builder.RegisterInstance<IBarService>( bar );
builder.RegisterType<Application>().SingleInstance();
return builder.Build();
}
This instantiates both services without their dependencies, and then sets them to each other afterward. By the time they are registered with the IoC container, their dependencies are completely set up.
See my Fiddle for a working example.
In provided examples, I would re-consider if you really have inter-service dependencies in those kind of situations:
Do you need logic contained in ICourseService in your RoomService implementation, or do you only need information from certain courses?
I would say that the latter one, so your real dependency could be ICourseRepository
with a method ICourseRepository.FindByRoom(Room room).
Do you need logic contained in IRoomService in your CourseService implementation, or do you only need existing rooms?
In this case, IRoomRepository could be enough.
However, it isn't always that easy and sometimes you really require logic implemented in Service layer, (validations, etc.). Trying to extract that behavior to shared classes rather than duplicating it or creating circular dependencies as mentioned can be preferrable in those scenarios.

How do I wire an IoC Container to pass a value to a factory method to resolve?

Background / Goal
We have several "client sites" on our web app that users can switch between
We do a lot of wiring up of objects based on factories that take in the client site ID and create an instance
I would like to inject these dependencies into the classes instead
I also want to make sure I can pass in my own implementations to the constructor for the purposes of unit testing.
We have initially elected to use StructureMap 3.x to do so, but are open to alternatives if they can help us solve this scenario gracefully.
Question
In instances where I require a different dependency based on a client site ID that I'll only get at run-time, what is the appropriate way to set up an IoC container and the appropriate way to request the object from it in order to make it as painless as possible?
Am I thinking about this wrong and unintentionally creating some sort of anti-pattern?
Example Code
Normally we're doing something like the following coming in:
public class MyService
{ DependentObject _dependentObject;
public MyService(int clientSiteID)
{
// ...
_dependentObject = new dependentObjectFactory(clientSiteID).GetDependentObject();
}
public void DoAThing()
{
//...
_dependentObject.DoSomething();
}
}
What I'd like to do:
public class MyService
{ DependentObject _dependentObject;
public MyService(int clientSiteID)
{
// ...
_dependentObject = MyTypeResolver.GetWIthClientContext<IDependentObject>(clientSiteID);
}
public MyService(int clientSiteID, IDependentObject dependentObject)
{
// ...
_dependentObject = dependentObject;
}
public void DoAThing()
{
//...
_dependentObject.DoSomething();
}
}
I would set up the IoC container in such a way that I can use my MyTypeResolver to pass in the clientSiteID, and have the container call my DependentObjectFactory and return the correct object result.
I'm new to IoC containers, and while I'm trying to plow through the literature, I have the feeling it may be easier than I'm making it so I'm asking here.
Probably the simplest way to do this is to use an Abstract Factory. Most IOC frameworks can auto-create them for you, but here's how you can do it manually (I always prefer to do it manually first so I know it works, and then you can check out how the framework can help you automagic it)
Now one thing to mention - I would recommend a slight readjustment of how the final solution works, but I'll go into that once I have shown how it can currently work. Example below assumes Ninject and please excuse any typos, etc.
First create an interface for your dependency
public interface IDependentObject
{
void DoSomething();
}
Then declare empty marker interfaces for each specific implementation of IDependentObject
public interface INormalDependentObject:IDependentObject{};
public interface ISpecialDependentObject:IDependentObject{}
and implement them:
public class NormalDependentObject:INormalDependentObject
{
readonly int _clientID;
public DependentObject(int clientID)
{
_clientID=clientID;
}
public void DoSomething(){//do something}
}
public class DependentObject:ISpecialDependentObject
{
readonly int _clientID;
public DependentObject(int clientID)
{
_clientID=clientID;
}
public void DoSomething(){//do something really special}
}
and of course as you mentioned you may have many more implementations of IDependentObject.
There may be a more elegant way of allowing your IOC framework to resolve at runtime without having to declare the marker interfaces; but for now I find it useful to use them as it makes the binding declarations easy to read :)
Next, declare an interface and implementation of an IDependentObjectFactory:
public interface IDependentObjectFactory
{
IDependentObject GetDependenObject(int clientID);
}
public class DependentObjectFactory: IDependentObjectFactory
{
readonly _kernel kernel;
public DependentObjectFactory(IKernel kernel)
{
_kernel=kernel;
}
public IDependentObject GetDependenObject(int clientID)
{
//use whatever logic here to decide what specific IDependentObject you need to use.
if (clientID==100)
{
return _kernel.Get<ISpecialDependantObject>(
new ConstructorArgument("clientID", clientID));
}
else
{
return _kernel.Get<INormalDependentObject>(
new ConstructorArgument("clientID", clientID));
}
}
}
Wire these up in your Composition Root:
_kernel.Bind<INormalDependentObject>().To<NormalDependentObject>();
_kernel.Bind<ISpecialDependentObject>().To<SpecialDependentObject>();
_kernel.Bind<IDependentObjectFactory>().To<DependentObjectFactory>();
and finally inject your factory into the service class:
public class MyService
{
IDependentObject _dependentObject;
readonly IDependentObjectFactory _factory;
//in general, when using DI, you should only have a single constructor on your injectable classes. Otherwise, you are at the mercy of the framework as to which signature it will pick if there is ever any ambiguity; most all of the common frameworks will make different decisions!
public MyService(IDependentObjectFactory factory)
{
_factory=factory;
}
public void DoAThing(int clientID)
{
var dependent _factory.GetDependentObject(clientID);
dependent.DoSomething();
}
}
Suggested changes
One immediate change from your structure above is that I have left clientID out of the service constructor and moved it to a method argument of DoAThing; this is because it makes a bit more sense to me that the Service itself would be stateless; of course depending on your scenario, you may want to not do that.
I mentioned that I had a slight adjustment to suggest , and it's this; the solution above depends (no pun!) on implementations of IDependentObject having a constructor with this signature:
public SomeDependency(int clientID)
If they don't have that signature then the factory won't work; personally I don't like my DI to have to know anything about constructor params because it takes you out of purely dealing with interfaces and forcing you to implement specific ctor signatures on your concrete classes.
It also means that you can't reliably make your IDependentObjects be part of the whole DI process (i.e whereby they themselves have dependency graphs that you want the framework to resolve) because of the forced ctor signature.
For that reason I'd recommend that IDependentObject.DoSomething() itself be changed to DoSomething(int clientID) so that you can elide the new ConstructorArgument part of the factory code; this means that your IDependentObject s can now all have totally different ctor signatures, meaning they can have different dependencies if needs be. Of course this is just my opinion, and you will know what works best in your specific scenario.
Hope that helps.

How to use a Provider in Ninject

I have the following code
public class Something {
[Inject]
public Configuration config {get;set;} //singleton
[Inject]
public Provider<WindowHandler> windowsProvider { get; set; } //NOT singleton
public void Search(string text) {
WindowHandler handler = windowsProvider.Create(xxxxxx);
//use the new handler that was created
}
}
but it seems the Provider takes an IContext where I put xxxxxx. Shouldn't the IContext from when I bootstrapped and created Something.cs from the kernel be used. Where is the no parameter Create method on the Provider??? (I am coming from Guice land point of view where it would be coded like above).
so the question is How do I do this correctly?
thanks,
Dean
It seems you are trying to use a provider as a factory in your code.
A provider in Ninject terms is a factory that is given to Ninject to create specially created objects. Therefore it gets the resolving context which can be used to create different instances depending where the instance in injected into.
public class FooProvider : Provider<IFoo>
{
public override IFoo CreateInstance(IContext ctx)
{
// add here your special IFoo creation code
return new Foo();
}
}
kernel.Bind<IFoo>().ToProvider<FooProvider>();
What you want is a factory in your coder that creates an instance of WindowHandler. Therefore create an interface to create the instance like this:
public interface IWindowHandlerFactory
{
WindowHandler Create();
}
Bind<IWindowHandlerFactory>().ToFactory();
Alternatively you can inject Func<WindowHandler> without adding a configuration. But this is less meaningful in my opinion.
NOTE: All this requires Ninject.Extensions.Factory available as prerelease 3.0.0-rc2 from Nuget.
See also: http://www.planetgeek.ch/2011/12/31/ninject-extensions-factory-introduction/
Well, my final solution was to cheat in ninject 2.0 with the following code...
var windowFactory = kernel.Get<IEWindowFactory>();
var tabFactory = kernel.Get<IETabFactory>();
windowFactory.Kernel = kernel;
tabFactory.Kernel = kernel;
and in the bindings list I have
Bind<IEWindowFactory>().ToSelf().InSingletonScope();
Bind<IETabFactory>().ToSelf().InSingletonScope();
and after that I just start my app
var main = kernel.Get<MainForm>();
main.Start();
and of course the factories are injected where I need them in the heirarchy of that MainForm.
so I manually put the kernel when starting up and then when I bootstrap my app, naturally these factories are fields in classes with [Ninject] annotation and so they can create objects. not the cleanest until we get 3.0, but it works(and I hate the extra factory classes I have to write code for but oh well).

Dependency injection with multiple repositories

I have a wcf service and on the client i have:
var service = new ServiceReference1.CACSServiceClient()
The actual service code is:
public CACSService() : this(new UserRepository(), new BusinessRepository()) { }
public CACSService(IUserRepository Repository, IBusinessRepository businessRepository)
{
_IRepository = Repository;
_IBusinessRepository = businessRepository;
}
So, all this works fine, but i don't like how i am newing up all the repositories at the same time because the client code might not need to new up the UserRepository and only interested in newing up the BusinessRepository. So, is there a way to pass in something to this code:
var service = new ServiceReference1.CACSServiceClient()
to tell it which repository to new up based on the code that is calling the service or any other advice i need to go about when designing the repositories for my entity framework. Thankx
The beauty of pure DI is that you shouldn't worry about the lifetimes of your dependencies, because these are managed for you by whoever supply them (a DI Container, or some other code you wrote yourself).
(As an aside, you should get rid of your current Bastard Injection constructors. Throw away the parameterless constructor and keep the one that explicitly advertises its dependencies.)
Keep your constructor like this, and use _IRepository and _IBusinessRepository as needed:
public CACSService(IUserRepository Repository, IBusinessRepository businessRepository)
{
_IRepository = Repository;
_IBusinessRepository = businessRepository;
}
If you worry that one of these repositories are not going to be needed at run-time, you can inject a lazy-loading implementation of, say, IUserRepsository instead of the real one you originally had in mind.
Let's assume that IUserRepository looks like this:
public interface IUserRepository
{
IUser SelectUser(int userId);
}
You can now implement a lazy-loading implementation like this:
public class LazyUserRepository : IUserRepository
{
private IUserRepository uRep;
public IUser SelectUser(int userId)
{
if (this.uRep == null)
{
this.uRep = new UserRepository();
}
return this.uRep.SelectUser(userId);
}
}
When you create CACService, you can do so by injecting LazyUserRepository into it, which ensures that the real UserRepository is only going to be initialized if it's needed.
The beauty of this approach is that you don't have to do this until you need it. Often, this really won't be necessary so it's nice to be able to defer such optimizations until they are actually necessary.
I first described the technique of Lazy Dependencies here and here.
Instead of instantiating ("newing up") the repositories on construction, you could lazy load them in their properties. This would allow you to keep your second constructor, but have your first constructor do nothing.
The user could then assign these, as needed, otherwise.
For example:
public class CACSService
{
public CACSService() {}
public CACSService(IUserRepository Repository, IBusinessRepository businessRepository)
{
_IRepository = Repository;
_IBusinessRepository = businessRepository;
}
private IUserRepository _IRepository;
public IUserRepository Repository
{
get {
if (this._IRepository == null)
this._IRepository = new UserRepository();
return this._IRepository;
}
}
// Add same for IBusinessRepository
}
Do your repositories have object-level state? Probably not, so create them as singletons and have a DI container provide them to CACService.
Otherwise, are they actually expensive to create? If not, creating a new one per request has negligible cost compared to the RPC and database operations.
Using the Ninject dependency injection container, your CACService might look like the following. Other DI containers have equally succinct mechanisms of doing this.
public class CACSService
{
public CACService
{
// need to do this since WCF creates us
KernelContainer.Inject( this );
}
[Inject]
public IUserRepository Repository
{ set; get; }
[Inject]
public IBusinessRepository BusinessRepository
{ set; get; }
}
And during your application startup, you would tell Ninject about these types.
Bind<IUserRepository>().To<UserRepository>().InSingletonScope();
Bind<IBusinessRepository>().To<BusinessRepository>().InSingletonScope();
Preface: This is a general guide to dependency inversion. If you need the default constructor to do the work (e.g. if it is new'ed up by reflection or something else), then it'll be harder to do this cleanly.
If you want to make your application configurable, it means being able to vary how your object graph is constructed. In really simple terms, if you want to vary an implementation of something (e.g. sometimes you want an instance of UserRepository, other times you want an instance of MemoryUserRepository), then the type that uses the implementation (CACService in this case) should not be charged with newing it up. Each use of new binds you to a specific implementation. Misko has written some nice articles about this point.
The dependency inversion principle is often called "parametrise from above", as each concrete type receives its (already instantiated) dependencies from the caller.
To put this into practice, move the object creation code out of the CACService's parameterless constructor and put it in a factory, instead.
You can then choose to wire up things differently based on things like:
reading in a configuration file
passing in arguments to the factory
creating a different type of factory
Separating types into two categories (types that create things and types that do things) is a powerful technique.
E.g. here's one relatively simple way of doing it using a factory interface -- we simply new up whichever factory is appropriate for our needs and call its Create method. We use a Dependency Injection container (Autofac) to do this stuff at work, but it may be overkill for your needs.
public interface ICACServiceFactory
{
CACService Create();
}
// A factory responsible for creating a 'real' version
public class RemoteCACServiceFactory : ICACServiceFactory
{
public CACService Create()
{
return new CACService(new UserRepository(), new BusinessRepository());
}
}
// Returns a service configuration for local runs & unit testing
public class LocalCACServiceFactory : ICACServiceFactory
{
public CACService Create()
{
return new CACService(
new MemoryUserRepository(),
new MemoryBusinessRepository());
}
}

Categories

Resources