Unity DI Container - Simple example request - injecting connection string in n-tier environment

Oct 31, 2008 at 11:26 PM
I just downloaded Unity DI Container and I am trying to implement it in my local environment.

It seems like the most basic and common example for DI would be a scenario where you have an n-tier environment and the database connection string needs to be passed to the business object solution.

How could I do this with Unity DI?  I started to create the following code from my main app but I was unsure about how to proceed....


//Instantiate a new UnityContainer.
UnityContainer container = new UnityContainer();



//Register an instance of the connection string with the container.
container.RegisterInstance(typeof(string), dbConnectionString);


Nov 1, 2008 at 1:04 PM
Edited Nov 1, 2008 at 1:05 PM
First of all for common types like string it is better to name what you've registered.

container.RegisterInstance(typeof(string), "ConnectionString", dbConnectionString,);

To use it put a Dependency attribute on a class that needs the connection string.
for example, like this:

public class SomeClass
     public string ConnectionString { private get; set; }

now when this class is resolved the property will be set.

SomeClass resolvedInstance = container.Resolve<SomeClass>();

Nov 2, 2008 at 3:22 AM

Thanks Danila - You're example helped a lot.  Now I am trying to use Unity to implement constructor injection. 

From what I can tell, Unity implements constructor injection through the RegisterType() method. 

First, I specify the parameter type - that's no problem.  But then do I need to specify the name of the parameter that's used in the constructor? 

Also, I can't quite figure out how to associate the parameter value with this approach.  Here is some code below.  The following code does not compile but I think that it shows what I am intending to do.

Can you show me the right way to do this?


string myConnectionString = "server=myserver;datasource=mydatasource";



string, "connectionString">(myConnectionString);