最近在用unity的依赖注入,但是园中类似UnityDependencyResolver 实现 IDependencyResolver的方式只能实现控制器的依赖注入,而ashx的就不行,无效,问问园中的大牛们可有良方啊?
以下是控制器依赖注入的实现代码,因为代码以复制到html格式上去就报错,所以直接以这样的形式贴出来了:
protected void Application_Start()
{
IUnityContainer container = GetUnityContainer();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
private IUnityContainer GetUnityContainer()
{
IUnityContainer container = new UnityContainer();
container.RegisterType<IRep_kk, Rep_kk>();接口和实现类
return container;
}
public class UnityDependencyResolver : IDependencyResolver
{
IUnityContainer container;
public UnityDependencyResolver(IUnityContainer container)
{
this.container = container;
}
public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType);
}
catch
{
return new List<object>();
}
}
}