Can Unity Framework instantiate a class in a different namespace than a given interface?
I have an interface:
namespace IF.Model
{
public interface IAll开发者_如何学编程ocationGroupRepository
{
}
}
and a class the implements that interface:
using IF.Model;
namespace IF.Repository
{
public class AllocationGroupRepository : IAllocationGroupRepository
{
}
}
In a Unity Framework call, I can .RegisterType() in the code for both of them:
IUnityContainer container = new UnityContainer();
container.RegisterType<IAllocationItemRepository, AllocationItemRepository>();
IAllocationItemRepository _allocationItemRepository = container.Resolve<IAllocationItemRepository>();
and .Resolve() works and gives me a new AllocationItemRepository object.
BUT, when I try to call Resolve and the mapping lives in the app.config file, I get this error:
"The current type, IF.Model.IAllocationItemRepository, is an interface and cannot be constructed. Are you missing a type mapping?"
Here is what my app.config file looks like:
<unity>
<containers>
<container>
<types>
<type
type="IF.Model.IAllocationGroupRepository, IF.Model"
mapTo="IF.Repository.AllocationGroupRepository, IF.Repository" />
</types>
</container>
</containers>
</unity>
here is what the code looks like trying to call .Resolve() using what's in the App.config file:
IUnityContainer container = new UnityContainer();
UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
section.Containers.Default.Configure(container);
IAllocationItemRepository _allocationItemRepository = container.Resolve<IAllocationItemRepository>();
as you can see, this is pretty basic stuff. Given an interface, resolve it to the class. It works when doing it inline, but fails when trying to do it from the app.config file.
What am I missing here?
Thanks, Mike
Try using aliases which call for the namespace as one of the parameters.
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IAllocationGroupRepository" type="IF.Model.IAllocationGroupRepository, IF.Model, Version=1.0.0.0, Culture=neutral"/>
<alias alias="AllocationGroupRepository" type="IF.Repository.AllocationGroupRepository, IF.Repository, Version=1.0.0.0, Culture=neutral"/>
<container>
<register type="IAllocationGroupRepository" mapTo="AllocationGroupRepository"/>
</container>
</unity>
However, why are you putting your repository interfaces in your model namespace? Would you, as a developer looking at that code for the first time, expect to find an IRepository interface in the Model namespace or the Repository namespace?
I'm assuming you a have unity reference, then you need to define your section name and its library. like so:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="mySectionName" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<mySectionName>
<typeAliases>
...
精彩评论