标签: ninject

Ninject绑定

如何将我的界面绑定到不同程序集中的具体类?

我的解决方案中有以下项目:

Foo.Data
Foo.Domain

在Structure Map中,我将两个程序集名称添加到StructureMap.config文件中,然后使用PluginFamily和Pluggable属性将我的接口映射到我的具体类'.

如何用Ninject完成同样的事情?

c# ninject

2
推荐指数
1
解决办法
5834
查看次数

Ninject Contextual binding

我大多使用Ninject的基本功能.因此,这个问题可能太明显了.如果是这样,请原谅.无论如何,我在模块中有以下内容:

Bind<Double>().ToConstant(TimeSpan.FromSeconds(10).TotalMilliseconds).Only(When.Context.Target.Name.AsString=="A");
Bind<Double>().ToConstant(TimeSpan.FromHours(1).TotalMilliseconds).Only(When.Context.Target.Name.AsString=="B");
Bind<Double>().ToConstant(TimeSpan.FromMinutes(5).TotalMilliseconds).Only(When.Context.Target.Name.AsString=="C");
Run Code Online (Sandbox Code Playgroud)

现在,问题是我如何使用kernel.get<Double>()解析我想要的上述任何一个绑定?

.net dependency-injection ninject

2
推荐指数
2
解决办法
2067
查看次数

使用现有的自定义基础从HttpHandler访问Ninject Kernel.Get()

我有一个ASP.Net webforms应用程序,它使用Ninject 2.2.0.0

我有一个HTTPHandler,它继承自Microsoft.Web.ImageHandler类.

在其中我需要访问我创建的服务类的实例.

因为我不能从Ninject.Web.HttpHandlerBase继承我认为我只是将内核暴露为Global.asax类的属性...

protected override IKernel CreateKernel()
    {
        IKernel kernel = new StandardKernel(new DefaultModule());

        var sms = kernel.Get<SiteMapService>();
        SiteMapSvc = sms;
        Kernel = kernel;
        return kernel;

    }

    public IKernel Kernel
    {
        get; set;
    }
Run Code Online (Sandbox Code Playgroud)

并使用kernel.Get方法获取服务..

var global = (Global) HttpContext.Current.ApplicationInstance;

var service = global.Kernel.Get<PhotoService>();
Run Code Online (Sandbox Code Playgroud)

这失败了以下......

   [ArgumentNullException: Cannot be null
Parameter name: root]
   Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot root, Type service, Func`2 constraint, IEnumerable`1 parameters, Boolean isOptional, Boolean isUnique) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:258
   Ninject.ResolutionExtensions.Get(IResolutionRoot root, Type service, IParameter[] parameters) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:151
   Thumb.GenerateImage(NameValueCollection parameters) in …
Run Code Online (Sandbox Code Playgroud)

webforms ninject httphandler

2
推荐指数
1
解决办法
3248
查看次数

在维护域驱动设计架构的同时,如何使用WCF服务设置Ninject?

我正在尝试实现一个概念验证,我在其中编写了一个模块(让我们说这个讨论的目的论坛)遵循领域驱动设计指南,并且将有一个可插拔的存储库,整个模块可以在Web服务器本地插入(本地托管的dll)或通过WCF服务.

遵循域驱动设计指南,我会有一组业务对象,可以像这样编写:

    public class Forum
    {
        readonly IRepository _forumRepository;
        public Forum(IRepository forumRepository)
        {
            _forumRepository = forumRepository;
        }

        public string Name { get; set; }

        public void Save()
        {
            _forumRepository.SaveForum(this);
        }
    }
Run Code Online (Sandbox Code Playgroud)

假设Web应用程序需要创建一个新论坛.

如果模块通过dll文件本地托管,这一切都很好.Web应用程序代码将简单地使用Ninject(或任何DI)来实例化业务对象并调用Save方法.

但是,如果实施者想在两者之间引入服务层呢?假设他们想在应用程序和数据库层之间引入WCF服务层,因为他们希望物理架构是Web Server - > App Server - > DB Server.显然,论坛模块dll将​​由Web服务器和应用服务器托管.但是,该模块不再可用.

如果Web服务器使用存储库注入实例化对象并将其传递到WCF服务层,则即使我允许将业务对象序列化,_forumRepository字段也会丢失.

实现者应该能够让应用服务器选择存储库.那么,有了这个要求,在从Web服务器接收到已经实例化的对象之后,实现者如何在应用服务器端注入存储库?有没有办法告诉WCF服务在反序列化过程中实例化对象时注入存储库?

我阅读了文章,如何在WCF服务中使用依赖注入(Ninject),并查看了示例解决方案,但这仅演示了如何将存储库直接注入服务.它似乎没有解决我在这里讨论的问题.

以下是我如何正确编写代码的例子.正如我之前所说,这里的主要问题是我不知道如何将存储库注入服务端的域对象.

应用程序代码(Web App或Windows App):

Forum newForum = new Forum();
//Set some properties on newForum.        
IKernel kernel = new StandardKernel();  //Instantiate ninject kernel.
//Yes, I know using the using statement means that IService …
Run Code Online (Sandbox Code Playgroud)

c# wcf domain-driven-design dependency-injection ninject

2
推荐指数
1
解决办法
1172
查看次数

Ncrunch所有测试通过首次运行,但在代码更改后和运行时按下所有按钮失败

我正在使用nunit和ninject在VS2012的新MVC 4解决方案中运行ncrunch.

当我第一次打开解决方案时,所有50个左右的测试运行并成功通过.

在我进行任何代码更改后(甚至只是添加了空白空间)ncrunch报告我的大部分单元测试都失败了.如果我在ncrunch窗口中按"运行所有测试",也会发生同样的事情.

但是,如果你点击"运行所有可见的测试"按钮,所有50次测试再次通过并且ncrunch报告一切正常.

此外,当您单独运行每个测试时,它们每次都会通过.

当它们失败时,它们似乎在我的ninject设置代码中失败了

错误:在ControllerTestSetup中TestFixtureSetUp失败

public class ControllerTestSetup
{

    [SetUp]
    public void InitIntegrationTest()
    {
        var context = IntegrationTestContext.Instance;
        context.Init();
        context.NinjectKernel.Load<MediGapWebTestModule>();
    }

    [TearDown]
    public void DisposeIntegrationTest()
    {
        IntegrationTestContext.Instance.Dispose();
    }
}

public class IntegrationTestContext : IDisposable
{  

    private static IntegrationTestContext _instance = null;
    private static readonly object _monitor = new object();

    private IntegrationTestContext() { }

    public static IntegrationTestContext Instance
    {
        get
        {
            if (_instance == null)
            {
                lock (_monitor)
                {
                    if (_instance == null)
                    {
                        _instance = new IntegrationTestContext(); …
Run Code Online (Sandbox Code Playgroud)

c# nunit ninject ncrunch

2
推荐指数
1
解决办法
1415
查看次数

使用Ninject将参数传递给Controller Constructor

这是一个MVC应用程序,其中控制器需要构造函数中的a DataContextCreator和a CustomerID.我ControllerFactory看起来像:

public class NinjectControllerFactory : DefaultControllerFactory
    {
        private IKernel ninjectKernel;

        public NinjectControllerFactory()
        {
            ninjectKernel = new StandardKernel();
            AddBindings();
        }


        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            if (controllerType == null)
            {
                return null;
            }
            else
            {
                string customerID =  requestContext.HttpContext.Session["CustomerID"].ToString();
                return (IController)ninjectKernel.Get(controllerType, new IParameter[]{new Parameter("CustomerID", customerID, true)});
            }
        }

        private void AddBindings()
        {
            ninjectKernel.Bind<IDataContextCreator>().To<DefaultDataContextCreator>();
        }
    }
Run Code Online (Sandbox Code Playgroud)

导航到页面时出现以下错误,即触发Controller的创建:

 Ninject.ActivationException: Error activating int
No matching bindings are available, and the type is not self-bindable.
Activation …
Run Code Online (Sandbox Code Playgroud)

ninject asp.net-mvc-3

2
推荐指数
1
解决办法
2717
查看次数

Ninject依赖注入:从配置读取绑定?

我是自动依赖注入的新手,并试图用MVC4应用程序干净地实现Ninject.一切都很实用,但我的强迫症想知道应用程序如何在NinjectWebCommon.cs中的RegisterServices(IKernel内核)方法中列出绑定.例如,

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        kernel.Bind<IAbstractManagerA>().To<ConcreteManagerA>();
        kernel.Bind<IAbstractManagerB>().To<ConcreteManagerB>();
        kernel.Bind<IAbstractRepoA>().To<ConcreteRepoA>();
        ...etc etc could be hundreds
    }    
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来处理这个?也许将每个配对作为web.config设置或其他配置文件?基本上为依赖注入注入依赖项:)

asp.net-mvc dependency-injection ninject inversion-of-control

2
推荐指数
1
解决办法
919
查看次数

如何使用Ninject Conventions Extension进行绑定?

我喜欢使用Ninject自动绑定绑定波纹管代码.是否可以在单个项目中同时使用手动和自动绑定?让我们采用波纹管手动绑定,我希望通过自动绑定实现.请告诉我如何实现这一目标.

  1. kernel.Bind<TestContext>().ToSelf().InRequestScope();

  2. kernel.Bind<IUnitOfWork<TestContext>>().To<UnitOfWork<TestContext>>();

Bellow所有接口都继承自基础接口:IRepository <Model>

3. kernel.Bind<IUserRepository>().To<UserRepository>();

4. kernel.Bind<IAccountRepository>().To<AccountRepository>();

5. kernel.Bind<IMessageRepository>().To<MessageRepository>().WithConstructorArgument("apikey", AppSettingsManager.GetSmsApiKey)

额外

我是否需要.Exclude<MessageRepository>()为多个类编写如果我需要这样做,如

.Exclude<ARepository>() .Exclude<BRepository>() .Exclude<CRepository>()

并且对于1和2是否需要单独的手动绑定?或者1可以使用BindToSelf()' and.Configure(b => b.InRequestScope())`

c# dependency-injection ninject ninject-extensions ninject.web.mvc

2
推荐指数
1
解决办法
4840
查看次数

通过Ninject内核是一个好习惯吗?

我正在编写一个执行几项任务的小框架.有些任务需要通过Ninject注入的特定属性.

假设我的基类中有以下构造函数,它代表一个Task:

protected DDPSchedulerTask(ILogger logger, List<string> platforms, IBackOfficeDataStore backOfficeDataStore, ICommonDataStore commonDataStore)
{
    _logger = logger;
    _platforms = platforms;
    _backOfficeDataStore = backOfficeDataStore;
    _commonDataStore = commonDataStore;
}
Run Code Online (Sandbox Code Playgroud)

所有任务都需要这些属性,因此我使用Ninject使用以下Ninject模块注入它们.

public class DDPDependencyInjectionBindingConfiguration : NinjectModule
{
    #region NinjectModule Members

    /// <summary>
    ///     Loads the module into the kernel.
    /// </summary>
    public override void Load()
    {
        Bind<Scheduler>().ToSelf(); // Make sure that the 'Scheduler' is resolved to itself.
        Bind<ILogger>().ToMethod(context => LogFactory.Create()); // Make sure that an instance of an ILogger is created through the LogFactory.

        // …
Run Code Online (Sandbox Code Playgroud)

c# ninject

2
推荐指数
1
解决办法
2172
查看次数

IoC容器中的自绑定是什么?

我已经看到像Ninject这样的框架以及Stack上的帖子都在使用依赖注入框架(例如下面的代码)时谈到了自绑定。

Bind<Samurai>().To<Samurai>();
Run Code Online (Sandbox Code Playgroud)

他们甚至为此具有特殊的语法:

Bind<Samurai>().ToSelf();
Run Code Online (Sandbox Code Playgroud)

为什么要将类型绑定到自身?我看不到有任何实用的应用程序可以解决此问题,并有助于减少代码中的依赖性。这是否仅意味着对类型的引用会简单地解决自身问题?

c# dependency-injection ninject ioc-container

2
推荐指数
1
解决办法
624
查看次数