我有以下(简化)情况:我有两个接口
interface IAmAnInterface
{
void DoSomething();
}
Run Code Online (Sandbox Code Playgroud)
和
interface IAmAnInterfaceToo
{
void DoSomethingElse();
}
Run Code Online (Sandbox Code Playgroud)
和一个实现两者的类:
class IAmAnImplementation: IAmAnInterface, IAmAnInterfaceToo
{
public IAmAnImplementation()
{
}
public void DoSomething()
{
}
public void DoSomethingElse()
{
}
}
Run Code Online (Sandbox Code Playgroud)
现在我使用Ninject将同一个类绑定到两个接口.因为我想要使用相同的IAmAnImplementationbeeing 实例,IAmAnInterface而且IAmAnInterfaceToo很明显我需要某种单例.我和ninject.extensions.namedscope一起玩,InScope()但没有成功.我的最后一次尝试是:
Bind<IAmAnImplementation>().ToSelf().InSingletonScope();
Bind<IAmAnInterface>().To<IAmAnImplementation>().InSingletonScope();
Bind<IAmAnInterfaceToo>().To<IAmAnImplementation>().InSingletonScope();
Run Code Online (Sandbox Code Playgroud)
但不幸的是,当我通过kernel.Get<IDependOnBothInterfaces>();它请求我的测试类的实例时实际上使用了不同的实例IAmAnImplementation.
class IDependOnBothInterfaces
{
private IAmAnInterface Dependency1 { get; set; }
private IAmAnInterfaceToo Dependency2 { get; set; }
public IDependOnBothInterfaces(IAmAnInterface i1, …Run Code Online (Sandbox Code Playgroud) c# dependency-injection ninject inversion-of-control ninject-3
我有例如2个interfases IInterface1和IInterface2,
public interface IInterface1 {...}
public interface IInterface2 {...}
Run Code Online (Sandbox Code Playgroud)
以及这些接口的一个实现ImplClass.
public class ImplClass : IInterface1, IInterface2 {...}
Run Code Online (Sandbox Code Playgroud)
我必须确保应用程序只有一个ImplClass实例,它将用作IInterface1和IInterface2.我正在使用ninject进行依赖注入.所以我的问题是:下面的代码是否符合我的要求?
...
Bind<IInterface1>().To<ImplClass>().Using<SingletonBehavior>();
Bind<IInterface2>().To<ImplClass>().Using<SingletonBehavior>();
...
Run Code Online (Sandbox Code Playgroud)
或者此代码将为eash接口创建2个ImplClass实例?
我有一个问题,似乎与http://markmail.org/message/6rlrzkgyx3pspmnf中描述的问题非常相似,如果您使用不同的服务类型访问它,实际上创建的单个实例不仅仅是单个实例.
我正在使用最新版本的Ninject 2 for Compact Framework,我遇到的确切问题是,如果我将相同的提供程序方法绑定到:
Func<Service> serviceCreator = () => new Service(false);
kernel.Bind<IService>().ToMethod(serviceCreator).InSingletonScope();
kernel.Bind<Service>().ToMethod(serviceCreator).InSingletonScope();
Run Code Online (Sandbox Code Playgroud)
如果我将它们解析为IService和Service,它似乎创建了2个Service实例.
这在解析Service时会导致循环依赖性异常.
这是设计,还是一个bug?