我试图按照这个博客来使用 Unity 实现依赖注入,但我在 boostrapper.cs 中遇到错误(我使用 Unity.MVC4 库)。有人可以指出我在这里缺少什么吗?
错误:IoCContainer 似乎没有实现 Microsoft.Practices.ServiceLocation.IServiceLocator。参数名称:commonServiceLocator
public static class Bootstrapper
{
public static IUnityContainer Initialise()
{
var container = BuildUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
// this throws "does not appear to implement Microsoft.Practices.ServiceLocation.IServiceLocator.... error"
DependencyResolver.SetResolver(new IoCContainer(container));
return container;
}
....
}
这是 IoCContainer 类
public class ScopeContainer : IDependencyScope
{
protected IUnityContainer container;
public ScopeContainer(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public object GetService(Type serviceType)
{
if (container.IsRegistered(serviceType))
{
return container.Resolve(serviceType);
}
else
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (container.IsRegistered(serviceType))
{
return container.ResolveAll(serviceType);
}
else
{
return new List<object>();
}
}
public void Dispose()
{
container.Dispose();
}
}
class IoCContainer : ScopeContainer, IDependencyResolver
{
public IoCContainer(IUnityContainer container)
: base(container)
{
}
public IDependencyScope BeginScope()
{
var child = container.CreateChildContainer();
return new ScopeContainer(child);
}
}
额外的!我在 app_start 中调用引导程序,我不确定它是否正确
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Bootstrapper.Initialise();
}
我也有一种感觉,它可能与路由有关,我实际上在配置中添加了经典的 MVC 路由,因为我读到 webapi 和 mvc 使用不同的“激活器”东西或类似的东西
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "RestApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);