Reputation: 3195
Unity config newbie, I am trying to implement this in my project. However, I am stuck.
I receive the following error: The current type, System.Web.Mvc.IControllerFactory, is an interface and cannot be constructed. Are you missing a type mapping?
ContainerClass
public class ContainerBootstrapper
{
public static void ConfigureUnityContainer()
{
//simple registeration
container.RegisterType<IProduct, ProductHelper>(); //maps interface to a concrete type
System.Web.Mvc.DependencyResolver.SetResolver(new MyProjectControllerDependency(container));
}
}
DependencyResolver
public class MyProjectControllerDependency : IDependencyResolver
{
private IUnityContainer _container;
public MyProjectControllerDependency(IUnityContainer container)
{
this._container = container;
}
public object GetService(Type serviceType)
{
return _container.Resolve(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _container.ResolveAll(serviceType);
}
Controller:
public class ProductController : ApiController
{
private readonly IProduct _iproduct;
public ProductController(IProduct product)
{
this._iproduct = product;
}
//controller methods
}
Interface
public interface IProduct
{
List<ProductViewModel> GetProductByBarcode(string value);
string GetProductPrice(string value);
}
Helper
public class ProductHelper : IProduct
{
//private readonly IProduct _iproduct;
//public ProductHelper(IProduct iproduct)
//{
// this._iproduct = iproduct;
//}
public List<ProductViewModel> GetProductByBarcode(string value)
{
throw new NotImplementedException();
}
public string GetProductPrice(string value)
{
throw new NotImplementedException();
}
}
I don't understand, what I am missing? Can anyone point me in the right direction.
Upvotes: 0
Views: 1527
Reputation: 6891
For ASP.NET MVC and WebApi projects using only Unity is not sufficient. For these projects you also need to install Unity.MVC
from nuget.
This is provides out of the box ready to use classes. You just need to register the dependencies in the UnityContainer and done.
Once you install Unity.MVC
, it creates classes UnityMvcActivator
and UnityConfig
. UnityConfig
class has implementation of initializing UnityContainer. All you need to do it register dependencies in RegisterTypes
method.
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IBaseClass, BaseClass>(); // Registering types
container.LoadConfiguration();
}
You don't need to create any custom type or implementation unless and until you have completely different requirement.
This should help you resolve your issue.
Upvotes: 1