So, here's a problem that I'm thinking about and could use some help with. Firstly, I'm using Unity for IOC, and want to use it to resolve and produce instances of a wrapper for my SQL calls. To do this, I have a SqlWrapper that implements ISqlWrapper. It has two contructors. Here's the relevent code snippet.
public interface ISqlWrapper : IDisposable
{
string CommandText { get; set; }
void Execute();
}
public class SqlWrapper : ISqlWrapper, IDisposable
{
public SqlWrapper(string connectionString);
public SqlWrapper(IDbConnection sqlConnection);
string CommandText { get; set; }
void Execute();
}
Obviously the about isn't the complete code, it's to illustrate the relevent part of the implementation.
For my application, I'm only using the contructor with the connectionString. So, in my IoC container, I've registered the following...
_unityContainerontainer.RegisterType<ISqlWrapper, SqlWrapper>( new InjectionConstructor(typeof(string)));
Now, this is where things get interesting. What I would like to do is implement a method that will allow me to easily resolve an instance of the ISqlWrapper. I've boilder the code down to this method.
ISqlWrapper CreateSqlWrapper(string connectionString)
{
ParameterOverrides parameterOverride = new ParameterOverrides();
parameterOverride.Add("connectionString", connectionString);
return _iocContainer.Resolve<ISqlWrapper>(parameterOverride);
}
However, currently I am putting a copy of this method into each class that I'm using to connect to my database.
public class ExampleClass1 : IExampleClass1
{
private readonly IIocContainer _iocContainer;
ISqlWrapper CreateSqlWrapper(string connectionString)
{
ParameterOverrides parameterOverride = new ParameterOverrides();
parameterOverride.Add("connectionString", connectionString);
return _iocContainer.Resolve<ISqlWrapper>(parameterOverride);
}
public ExampleClass1(IIocContainer iocContainer)
{
_iocContainer = iocContainer;
}
public void DoStuff(string connectionString)
{
using( ISqlWrapper sqlWrapper = CreateSqlWrapper(connectionString))
{
CommandText = "Select * from Table*";
Execute;
}
}
}
So, the problem is that I need to have an instance of CreateSqlWrapper in every class to make implementing an instance of ISqlWrapper easier. I know that I could use inheritance to implement this method into a parent class. However, I'm trying to see if there is a better solution to this problem.
Does anyone have any ideas of how I can define the CreateSqlWrapper method without needing to copy and paste it into every class?