标签: ninject

从 Ninject 2 移至 Ninject 3。绑定出错。确保提供者正确处理创建请求

我刚刚使用 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)

ninject

3
推荐指数
1
解决办法
1940
查看次数

自定义依赖关系解析器会降低我的MVC应用程序吗?

不会为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)

c# asp.net-mvc dependency-injection ninject

3
推荐指数
1
解决办法
456
查看次数

Ninject拦截不会在同一个类中使用嵌套方法调用触发

我是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)

c# aop ninject inversion-of-control

3
推荐指数
1
解决办法
364
查看次数

F#中带有可选参数的MVC控制器

我相应地创建带有可选参数的控制器:

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-mvc f# ninject

3
推荐指数
1
解决办法
670
查看次数

小代码修改后“无法访问已处理的对象”

使用 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, …

asp.net ninject asp.net-identity-2

3
推荐指数
1
解决办法
3137
查看次数

如何在 Ninject 中使用“复合设计模式”

验证规则合约:

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我想要获取IValidationRuleValidationRuleComposite.

我如何使用 Ninject 实现这一目标?

c# dependency-injection ninject composite ioc-container

3
推荐指数
1
解决办法
841
查看次数

使用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)

c# ninject

3
推荐指数
1
解决办法
8398
查看次数

Akka.NET DI on Windows 服务和最佳实践

我正在尝试将 Windows 服务的一部分迁移到 AKKA.net 参与者模型中,但是当涉及到参与者的 DI(他们有一些依赖项,例如数据访问层等)时,我遇到了一些问题,因为我不完全了解如何在服务中连接 DependencyResolver。如果那是一个 Web 应用程序,那么它将是 HttpConfiguraiton 的 DependencyResolver 但是在这种情况下,我目前拥有标准内核来进行引导并获取顶级接口实现以启动 Windows 服务。

我会有两个问题:

  • 在 Windows 服务中为 actor 配置 DI 的方法是什么?
  • 从另一个类中获取系统参与者的最佳方法是什么?

我一直在这里阅读:http : //getakka.net/docs/Dependency%20injection#ninject

提前致谢!

windows-services dependency-injection ninject akka.net

3
推荐指数
1
解决办法
1100
查看次数

为什么我们在 ninject 中使用 .ToSelf() 背后的主要逻辑是什么

我正在研究 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

3
推荐指数
1
解决办法
1425
查看次数

Ninject,如何通过调用 LoggerFactory.CreateLogger 注入一个通用的 Logger&lt;T&gt;

我正在开发一个 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)

asp.net-mvc dependency-injection ninject ninject-extensions

3
推荐指数
1
解决办法
2772
查看次数