Reputation: 21328
I'm working with .net 4.5 and MVC4. I implemented Unity IoC as described in the following post: http://kennytordeur.blogspot.com/2011/05/aspnet-mvc-3-and-unity-using.html
But I would like to be able to have "register" my repository types using an external XML or within web.config. Is that possible?, samples would be greatly appreciated.
thanks
Upvotes: 1
Views: 2555
Reputation: 172676
Unless there is a really strong reason to, you should register as much as possible in code. XML configuration is much more error prone, verbose and can become a maintenance nightmare very quickly. Instead of registering (all) your repository types in XML (which is possible with Unity), just put the assembly name containing that contains the repository types in the config and register them dynamically in code. This saves you from having to change the configuration every time you add a new repository implementation.
Here is an example.
In your configuration file, add a new appSetting with the name of the assembly:
<appSettings>
<add key="RepositoryAssembly" value="AssemblyName" />
</appSettings>
In your composition root, you can do the following:
var assembly = Assembly.LoadFrom(
ConfigurationManager.AppSettings["RepositoryAssembly"]);
// Unity misses a batch-registration feature, so you'll have to
// do this by hand.
var repositoryRegistrations =
from type in assembly.GetExportedTypes()
where !type.IsAbstract
where !type.IsGenericTypeDefinition
let repositoryInterface = (
from _interface in type.GetInterfaces()
where _interface.IsGenericType
where typeof(IRepository<>).IsAssignable(
_interface.GetGenericTypeDefinition())
select _interface)
.SingleOrDefault()
where repositoryInterface != null
select new
{
service = repositoryInterface,
implemention = type
};
foreach (var reg in repositoryRegistrations)
{
container.RegisterType(reg.service, reg.implementation);
}
The LINQ query has a lot of subtle defects (for instance, it lacks checks for generic type constraints), but it will work for the common scenarios. If you work with generic type constraints, you should definitely switch to a framework that has support for this, because this is something that's really hard to get right.
Upvotes: 3