StructureMap singleton usage (A class implementing two interface)

后端 未结 4 426
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-01 04:46
public interface IInterface1
{
}

public interface IInterface2
{
}

public class MyClass : IInterface1, IInterface2
{
}

...

ObjectFactory.Initialize(x =>
{
             


        
相关标签:
4条回答
  • 2020-12-01 04:48

    An ObjectFactory is intended to create multiple instances. If you want a singleton, write a singleton class (perhaps with public IInterface1 and IInterface2 properties as accessors).

    It seems sketchily documented, but perhaps you can use a Container instead.

    0 讨论(0)
  • 2020-12-01 04:49

    I would register the MyClass itself and then pull that out of the context for the Use statements of the individual interfaces.

    ForSingletonOf<MyClass>().Use<MyClass>();
    
    For<IInterface1>().Use(ctx => ctx.GetInstance<MyClass>());
    For<IInterface2>().Use(ctx => ctx.GetInstance<MyClass>());
    
    0 讨论(0)
  • 2020-12-01 04:59

    Try looking at the different overloads to Use, especially Func overload. From there you can tell how StructureMap should create your instance with another object already registred.

    0 讨论(0)
  • 2020-12-01 05:05

    You can use the Forward<,>() registration to tell StructureMap to resolve a type using the resolution of a different type. This should do what you expect:

    ObjectFactory.Initialize(x =>
    {
        x.For<IInterface1>().Singleton().Use<MyClass>();
        x.Forward<IInterface1, IInterface2>();
    });
    
    0 讨论(0)
提交回复
热议问题