我刚刚使用 Ninject 3 更新了我的应用程序。将 App_Start 中的文件从 NinjectMVC3 更改为 NinijectWebCommon.cs。移动了我的文件,更新了 DLL。现在我开始收到此错误:
“使用 Dictionary{string, string} Provider 的条件隐式自绑定激活 Dictionary{string, string} 时出错,返回 null。激活路径:4) 将依赖项 Dictionary{string, string} 注入到 MapWidgetViewModel 类型的构造函数的参数 widgetSettings 3)将依赖项 IDetailedSearchResultCollectionWidget 注入 MediaSourcesViewModel 类型的构造函数的参数 mediaWidgets 2) 将依赖项 ITabItem 注入 TabNavigationController 类型的构造函数的参数 tabItems 1) 请求 TabNavigationController
建议:1)确保提供商正确处理创建请求。”
在这里生成它的代码:
public MediaSourcesViewModel(IEnumerable<IMediaSourcesDataProvider> dataProviders,
IEnumerable<IDetailedSearchResultCollectionWidget> mediaWidgets,
IMediaItemDetailsWidget itemDetailsWidget)
{
this.Description = "Source list";
this.ActionName = "DisplaySourcesAsPartial";
this.ControllerName = "MediaSources";
this.DefaultType = "MediaManagement";
_dataProviders = dataProviders;
MediaWidgets = new List<IDetailedSearchResultCollectionWidget>();
MediaWidgets.AddRange(mediaWidgets); //Set Tab Info
this.Name = "Sources";
} …Run Code Online (Sandbox Code Playgroud) 不会为asp.net MVC 4使用自定义依赖项解析器显着减慢应用程序?考虑到它被调用每个单独的依赖,而不仅仅是我需要它被调用(下面)
有没有办法让GetService(Type serviceType)我有一个ninject可以解析的接口,而不是asp.net为每个单独的依赖项调用GetService,如下所示,以使其更快?我正在使用Ninject,这不是最快的开始.
或者这是我不应该担心的事情?谢谢
public class NinjectDependencyResolver : IDependencyResolver
..... unnecessary code not shown
public object GetService(Type serviceType)
{
Debug.WriteLine("GetService was called for " + serviceType.ToString());
return kernel.TryGet(serviceType);
}
Run Code Online (Sandbox Code Playgroud)
输出窗口正在显示
GetService was called for System.Web.Mvc.ITempDataProvider
GetService was called for System.Web.Mvc.Async.IAsyncActionInvoker
GetService was called for System.Web.Mvc.IActionInvoker
GetService was called for System.Web.Mvc.IViewPageActivator
GetService was called for ASP._Page_Views_Home_Index_cshtml ... GOES ON and ON....
Run Code Online (Sandbox Code Playgroud) 我是Ninject的新手,我试图拦截一个类中的两个方法.第一种方法被截获.第一种方法调用第二种方法,但后者不触发拦截器.
有解决方案吗?
这是一些代码:
public interface IJobMonitor
{
void Run();
JobCheck ManageJob(JobCheck job);
}
[LogAround]
public class JobMonitor : IJobMonitor {
public virtual void Run(){
//boilerplate
var job = ManageJob(new JobCheck());
}
public virtual JobCheck ManageJob(JobCheck job) {
//lots of good stuff
}
}
public class LogAroundAttribute : InterceptAttribute
{
public override IInterceptor CreateInterceptor(IProxyRequest request)
{
return request.Kernel.Get<LogAroundInterceptor>();
}
}
public class LogAroundInterceptor : IInterceptor
{
private readonly ILogger _logger;
public LogAroundInterceptor(ILogger logger)
{
_logger = logger;
}
public void Intercept(IInvocation …Run Code Online (Sandbox Code Playgroud) 我相应地创建带有可选参数的控制器:
type ProductController(repository : IProductRepository) =
inherit Controller()
member this.List (?page1 : int) =
let page = defaultArg page1 1
Run Code Online (Sandbox Code Playgroud)
当我启动应用程序时,它给了我错误:“ System.MissingMethodException:没有为此对象定义无参数构造函数。 ”
我知道依赖注入的这个错误,这是我的 Ninject 设置:
static let RegisterServices(kernel: IKernel) =
System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver <- new NinjectResolver(kernel)
let instance = Mock<IProductRepository>()
.Setup(fun m -> <@ m.Products @>)
.Returns([
new Product(1, "Football", "", 25M, "");
new Product(2, "Surf board", "", 179M, "");
new Product(3, "Running shoes", "", 95M, "")
]).Create()
kernel.Bind<IProductRepository>().ToConstant(instance) |> ignore
do()
Run Code Online (Sandbox Code Playgroud)
问题是当我从控制器中删除我的可选参数时一切正常。当更改常规参数时,它给我以下错误: 参数字典包含一个空条目,用于方法 'System.Web.Mvc.ViewResult List(Int32)' 的不可为空类型 'System.Int32' 的参数 'page' 'FSharpStore.WebUI.ProductController'。可选参数必须是引用类型、可为空类型或声明为可选参数。参数名称:参数 …
使用 ASP.NET MVC5、EF6 和 Ninject 作为后端,AngularJS 作为前端,使用基于令牌的身份验证 (JWT)。
我们最近不得不在用户名中启用@chars。基于Startup.cs 中的这个答案(由 Ninject 注册代码调用,见下文),我们替换了
UserManagerFactory = () => new ApplicationUserManager(new UserStore<IdentityUser>(new SecurityDbContext()));
Run Code Online (Sandbox Code Playgroud)
和
var userManager = new ApplicationUserManager(new UserStore<IdentityUser>(new SecurityDbContext()));
var validator = new UserValidator<IdentityUser>(userManager)
{
AllowOnlyAlphanumericUserNames = false
};
userManager.UserValidator = validator;
UserManagerFactory = () => userManager;
Run Code Online (Sandbox Code Playgroud)
这允许根据需要使用@ 符号注册用户名。但是,登录应用程序(即使使用“普通”用户名)变得有问题:虽然服务器启动后的第一次登录照常工作,但任何后续登录都会产生以下异常:
Cannot access a disposed object.
Object name: 'ApplicationUserManager'.
Run Code Online (Sandbox Code Playgroud)
详细的错误信息:
源错误:
第 18 行:public override async Task FindAsync(string userName, string password)
第 19 行:{
第 20 行:var result = await base.FindAsync(userName, … 验证规则合约:
public interface IValidationRule
{
bool IsValid();
}
Run Code Online (Sandbox Code Playgroud)
具体验证规则:
public class MyClass : IValidationRule
{
public bool IsValid()
{
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
合成的:
public class ValidationRuleComposite : IValidationRule
{
private readonly IEnumerable<IValidationRule> _validationRules;
public ValidationRuleComposite(IEnumerable<IValidationRule> validationRules)
{
_validationRules = validationRules;
}
public bool IsValid()
{
return _validationRules.All(x => x.IsValid());
}
}
Run Code Online (Sandbox Code Playgroud)
当我向容器询问时,IValidationRule我想得到ValidationRuleComposite. 如果我向容器询问IValidationRule我想要获取IValidationRule除ValidationRuleComposite.
我如何使用 Ninject 实现这一目标?
如何使用Ninject获取单个实例?这是我的服务模块:
public class ServicesModule : NinjectModule
{
public override void Load()
{
Kernel.Bind<IDocumentServiceApi>().To<DocumentServiceApi>().InRequestScope();
Kernel.Bind<IConfigurationService>().To<ConfigurationService>().InRequestScope();
Kernel.Bind<IReportGenerationProcessor>().To<ReportGenerationProcessor>().InRequestScope();
}
}
Run Code Online (Sandbox Code Playgroud)
我需要一个实例IReportGenerationProcessor来触发我从Azure服务总线队列收到的消息.
我见过很多不同的方法,但没有一个对我有用.我不断得到错误:Object instance not set to an instance of an object.
//I do instantiate this class using new WebJobBase();
public class WebJobBase
{
public void ProcessMessage(BrokeredMessage message)
{
// Just need an instance of IReportGenerationProcessor here
var _processor = new ReportGenerationProcessor();
_processor.ProcessMessage(message);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的IReportGenerationProcessor实现:
public interface IReportGenerationProcessor
{
DocumentMetaData ProcessMessage(BrokeredMessage message);
}
public class ReportGenerationProcessor : …Run Code Online (Sandbox Code Playgroud) 我正在尝试将 Windows 服务的一部分迁移到 AKKA.net 参与者模型中,但是当涉及到参与者的 DI(他们有一些依赖项,例如数据访问层等)时,我遇到了一些问题,因为我不完全了解如何在服务中连接 DependencyResolver。如果那是一个 Web 应用程序,那么它将是 HttpConfiguraiton 的 DependencyResolver 但是在这种情况下,我目前拥有标准内核来进行引导并获取顶级接口实现以启动 Windows 服务。
我会有两个问题:
我一直在这里阅读:http : //getakka.net/docs/Dependency%20injection#ninject
提前致谢!
我正在研究 Ninject 作为新的我有一个来自“战士模块”类下面的代码的问题我们已经绑定了类的接口,但是为什么我们使用 .ToSelf() 和类 SWORD 我已经完成了谷歌,但我无法得到确切的逻辑在这背后..如果我删除这条线怎么办
Bind<Sword>().ToSelf();
Run Code Online (Sandbox Code Playgroud)
下面的代码
//interface
interface IWeapon
{
void Hit(string target);
}
//sword class
class Sword : IWeapon
{
public void Hit(string target)
{
Console.WriteLine("Killed {0} using Sword", target);
}
}
class Soldier
{
private IWeapon _weapon;
[Inject]
public Soldier(IWeapon weapon)
{
_weapon = weapon;
}
public void Attack(string target)
{
_weapon.Hit(target);
}
}
class WarriorModule : NinjectModule
{
public override void Load()
{
Bind<IWeapon>().To<Sword>();
Bind<Sword>().ToSelf();//why we use .Toself() with self
}
}
static void …Run Code Online (Sandbox Code Playgroud) c# asp.net-mvc dependency-injection ninject inversion-of-control
我正在开发一个 ASP.NET MVC 应用程序。
我已经在从 Global.asax 调用的静态类中初始化了我的 LoggerFactory
using Microsoft.Extensions.Logging;
using Serilog;
using System.IO;
namespace web
{
public static class LogConfig
{
public static LoggerFactory LoggerFactory = new LoggerFactory();
public static void RegisterLogger()
{
LoggerFactory = new LoggerFactory();
Log.Logger = new LoggerConfiguration().MinimumLevel.Debug().WriteTo.RollingFile(Path.Combine("", "log-{Date}.txt")).CreateLogger();
LoggerFactory.AddSerilog();
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在我想使用 ninject,将 ILogger 的一个实例注入到我的构造函数中......
在我的构造函数中,我有:
private ILogger<MyTypeController> _logger;
public MyTypeController(ILogger<MyTypeController>)
{
// This works fine but I want to inject it
_logger = LogConfig.LoggerFactory.CreateLogger<MyTypeController>();
}
Run Code Online (Sandbox Code Playgroud)
上面的代码有效,但我想使用 ninject 注入它……这是我尝试过的,但甚至没有编译:
kernel.Bind(typeof(ILogger<>)).ToProvider(LogConfig.LoggerFactory.CreateLogger<>());
Run Code Online (Sandbox Code Playgroud)