我有一个ASP.NET MVC 4.7.2项目。我使用NInject(今天更新为)3.3.4来维护依赖关系。我不使用NInject推送的web.Common常用功能。相反,我有:
public static class ResolverConfig
{
public static void RegisterResolver()
{
INinjectModule module = new MyModule();
IResolutionRoot kernel = new StandardKernel(module);
NinjectDependencyResolver resolver = new NinjectDependencyResolver(kernel);
DependencyResolver.SetResolver(resolver);
}
}
其中哪个位于global.asax中:
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
ResolverConfig.RegisterResolver();
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
NinjectDependencyResolver为:
public class NinjectDependencyResolver :
NinjectDependencyScope,
System.Web.Http.Dependencies.IDependencyResolver,
System.Web.Mvc.IDependencyResolver
{
public NinjectDependencyResolver(IResolutionRoot resolver) : base(resolver)
{
}
public System.Web.Http.Dependencies.IDependencyScope BeginScope()
{
return new NinjectDependencyScope(Resolver);
}
}
我对Web Api和Web页面使用相同的解析器。 NinjectDependencyScope:
public class NinjectDependencyScope: IDependencyScope
{
public NinjectDependencyScope(IResolutionRoot resolver)
{
Resolver = resolver ?? throw new ArgumentNullException(nameof(resolver));
}
protected IResolutionRoot Resolver { get; }
public void Dispose()
{
}
public object GetService(Type serviceType)
{
object instance = null;
if (serviceType != null)
{
instance = Resolver.TryGet(serviceType);
}
return instance;
}
public IEnumerable<object> GetServices(Type serviceType)
{
var all = serviceType != null ?
Resolver.GetAll(serviceType) :
new object[0];
return all;
}
这已经为我工作了一段时间。今天我有一个Home控制器:
public class HomeController: Controller
{
public HomeController(IFindTerminalState engine, IWriteSubscriptionRecord writer)
{
Engine = engine;
Writer = writer;
}
private IFindTerminalState Engine { get; }
private IWriteSubscriptionRecord Writer { get; }
[Route("Home/Index/{email?}/{returnUrl?}")]
public async Task<ActionResult> Index(...)
{
....
}
...
}
我有一个模块:
public class MyModule: NinjectModule
{
public override void Load()
{
...
Bind<IFindTerminalState>().To<FindTerminalState>();
...
string subscriptionApi = ...
Bind<IWriteSubscriptionRecord>()
.To<WriteMySubscriptionRecord>()
.WithConstructorArgument("subscriptionApi", subscriptionApi);
}
}
注入到HomeController中的两个服务都在模块中。我启动了网站并导航到〜/ Home / Index / bob @ example%2Ecom / example%2Ecom。我收到一个异常消息:“没有为此对象定义无参数的构造函数。”该代码一直有效到现在。知道错误在哪里吗?
答案 0 :(得分:0)
我是个白痴。 IWriteSubscriptionRecord服务本身具有依赖项,但我没有注意到。 Ninject模块尚未完成。