How do I correctly use Unity to pass a ConnectionString to my repository classes?
Posted
by GenericTypeTea
on Stack Overflow
See other posts from Stack Overflow
or by GenericTypeTea
Published on 2010-05-09T08:14:13Z
Indexed on
2010/05/09
8:18 UTC
Read the original article
Hit count: 381
I've literally just started using the Unity Application Blocks Dependency Injection library from Microsoft, and I've come unstuck.
This is my IoC class that'll handle the instantiation of my concrete classes to their interface types (so I don't have to keep called Resolve on the IoC container each time I want a repository in my controller):
public class IoC
{
public static void Intialise(UnityConfigurationSection section,
string connectionString)
{
_connectionString = connectionString;
_container = new UnityContainer();
section.Configure(_container);
}
private static IUnityContainer _container;
private static string _connectionString;
public static IMovementRepository MovementRepository
{
get
{
return _container.Resolve<IMovementRepository>();
}
}
}
So, the idea is that from my Controller, I can just do the following:
_repository = IoC.MovementRepository;
I am currently getting the error:
Exception is: InvalidOperationException - The type String cannot be constructed. You must configure the container to supply this value.
Now, I'm assuming this is because my mapped concrete implementation requires a single string parameter for its constructor. The concrete class is as follows:
public sealed class MovementRepository : Repository, IMovementRepository
{
public MovementRepository(string connectionString) : base(connectionString) { }
}
Which inherits from:
public abstract class Repository
{
public Repository(string connectionString)
{
_connectionString = connectionString;
}
public virtual string ConnectionString
{
get { return _connectionString; }
}
private readonly string _connectionString;
}
Now, am I doing this the correct way? Should I not have a constructor in my concrete implementation of a loosely coupled type? I.e. should I remove the constructor and just make the ConnectionString property a Get/Set so I can do the following:
public static IMovementRepository MovementRepository
{
get
{
return _container.Resolve<IMovementRepository>(
new ParameterOverrides
{
{
"ConnectionString", _connectionString
}
}.OnType<IMovementRepository>() );
}
}
So, I basically wish to know how to get my connection string to my concrete type in the correct way that matches the IoC rules and keeps my Controller and concrete repositories loosely coupled so I can easily change the DataSource at a later date.
© Stack Overflow or respective owner