public interface IInterface1
{
}

public interface IInterface2
{
}

public class MyClass : IInterface1, IInterface2
{
}

...

ObjectFactory.Initialize(x =>
{
    x.For<IInterface1>().Singleton().Use<MyClass>();
    x.For<IInterface2>().Singleton().Use<MyClass>();
});

var x = ObjectFactory.GetInstance<IInterface1>();
var y = ObjectFactory.GetInstance<IInterface2>();

我用上面的代码得到了两个不同的MyClass实例。我怎么能得到一个?

最佳答案

您可以使用Forward ()注册来告诉StructureMap使用其他类型的分辨率来解析类型。这应该可以实现您的期望:

ObjectFactory.Initialize(x =>
{
    x.For<IInterface1>().Singleton().Use<MyClass>();
    x.Forward<IInterface1, IInterface2>();
});

关于c# - StructureMap单例用法(实现两个接口(interface)的类),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2363458/

10-10 15:58