当我在应用程序中注册Unity时,它会抛出
尝试创建类型为'InvoiceController'的控制器时发生错误。确保控制器具有无参数的公共构造函数
我经过漫长而艰苦的搜索,但发现了很多文章,我全都关注了他们,但没有成功。
1-已安装Unity ConfigureUnity文件:
2-添加了以下两个类 ConfigureUnity类
git branch -D branch-new
git checkout -b branch-new
-UnityResolver
public static void ConfigureUnity(HttpConfiguration config)
{
var container = new UnityContainer();
container.RegisterType<IInvoiceService, InvoiceService>();
container.RegisterType<IInvoiceRepository, InvoiceRepository>();
config.DependencyResolver = new UnityResolver(container);
}
3-在WebApiConfig中注册它。
public class UnityResolver : IDependencyResolver
{
protected IUnityContainer container;
public UnityResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}
public IDependencyScope BeginScope()
{
var child = container.CreateChildContainer();
return new UnityResolver(child);
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
container.Dispose();
}
}
然后我像下面那样在控制器中使用它
public static void Register(HttpConfiguration config)
{
UnityConfig.ConfigureUnity(config);
}
我试图添加一个空的构造函数,APIController始终使用它。 我要去哪里错了?我真的不知道该怎么办。