Reputation: 179
I am currently in the process of re-factoring an existing application which is a few years old so that we can use dependency injection (which I am new to) to inject which sync provider I want to use.
I am struggling to work out how to setup the interfaces and factories as the class I am working on has multiple constructors.
I will try and lay this out as best as I can. I have a Sync class that is accessed via multiple parts of the application which has 4 constructors which are all used.
Sync.cs
public class Sync : ISync
{
private static Hashtable _locks = new Hashtable();
private CSettings _cs = null;
private RemovedCallback _callback = null;
protected object _cObject = null;
protected bool _isLocked = false;
private DateTime _expires = DateTime.MinValue;
public Sync() { }
public Sync(CSettings cs) : this(cs, null) { }
public Sync(CSettings cs, RemovedCallback callback)
{
Callback = callback;
Settings = cs;
}
public Sync(string key)
{
Settings = new CSettings();
Settings.Key = key;
}
public object Object
{
get { return Get(); }
set { Set(value); }
}
public void Get()
{
}
public void Set()
{
}
//other methods, some that reference Remove and Set
}
ISync.cs
public interface ICacheSync : IDisposable
{
object Get();
void Set(object obj);
}
SyncProvider.cs
public class SyncProvider : ISync
{
public override object Get()
{
//some code
}
public override void Set(object obj)
{
//some code
}
}
In the Sync class, the Get and Set methods will be different for each Sync provider that I inject. The rest of the Sync class needs to remain the same.
My end goal is to be able to inject different Sync Providers that use Get and Set in different ways.
Currently the Sync class is referenced throughout this project the following way:
Example 1
using (Sync sync = new Sync(CSettings, ItemRemoved))
{
//some code
}
Example 2
using (Sync sync = new Sync(CSettings))
{
sync.Remove();
}
Example 3
using (Sync sync = new Sync(string))
{
sync.Remove();
}
I am using Ninject and have tried a ways of creating interfaces and injecting but it just doesn't seem to work as I always end up with Object Reference not set to instance of Object errors.
Any help or guidance on how to go about this would be massively helpful in assisting me to understand DI more.
Upvotes: 0
Views: 155
Reputation: 994
In this instance I would advise you use a Factory, rather than dependency injection.
The factory itself can be injected into the classes that currently construct Sync instances, but instead of directly 'new'-ing up the Sync objects, you would delegate that to the SyncFactory:
using (Sync sync = this.syncFactory.Create(CSettings, ItemRemoved))
{
//some code
}
using (Sync sync = this.syncFactory.Create(CSettings))
{
//some code
}
using (Sync sync = this.syncFactory.Create(stringValue)
{
sync.Remove();
}
Upvotes: 1