I am trying to use Unity 2.0 for my current project with MVC and cannot configure the parameterization setting in the web.config file.
Here is what I have:
1) Home controller:
public class HomeController : Controller
{
IRepository repository = null;
public HomeController()
{
}
public HomeController(IRepository repository)
{
this.repository = repository;
}
public ActionResult Index()
{
List<int> intList = this.repository.GetInts();
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
Basic controller with two constructors. The first takes no arguments, and the second takes an IRepository as an argument (which must be entered by Unity)
2) SQL repository
public class SQLRepository : IRepository
{
private string connectionString = null;
public SQLRepository(string connectionString)
{
this.connectionString = connectionString;
}
#region IRepository Members
public List<int> GetInts()
{
return new List<int>() { 1, 2, 3, 4, 5 };
}
#endregion
}
The future is an SQL repository, but at the moment it just implements 1 member of the IRepository interface, namely GetInts () and returns a list of integers.
3) IRepository Interace
public interface IRepository
{
List<int> GetInts();
}
Interface.
4) Application_Start ( ) event in the Global.asax file.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
IUnityContainer container = new UnityContainer();
UnityConfigurationSection section = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;
section.Configure(container, "Default");
}
Unity 2.0 web.config ..
6) Unity 2.0 web.config
<unity>
<typeAliases>
<typeAlias alias="string" type="System.String, mscorlib" />
<typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
<typeAlias alias="IRepository" type="NewMVCApp.Interfaces.IRepository, NewMVCApp" />
<typeAlias alias="SQLRepository" type="NewMVCApp.Repository.SQLRepository, NewMVCApp" />
</typeAliases>
<containers>
<container name="Default">
<types>
<type type="IRepository" mapTo="SQLRepository">
<lifetime type="singleton" />
<constructor>
<param name="connectionString">
<value value="ApplicationServices" />
</param>
</constructor>
</type>
</types>
</container>
</containers>
Unity 2.0, . , TypeAlias IRepository SQLRepository, IRepository SQLRepository. IRepository , SQLRepository. , SQLRepository.
5) , ?
Unity 2.0 IRepository (SQLRepository) HomeController. - defaultless HomeController(). HomeController ( IRepository) . , web.config. , , HomeController. , :)
& :)