开发者

Initialising StructureMap with class that has a constructor with parameters

I am trying to initialise StructureMap to inject a concrete class which has only one constructor which takes 4 string parameters.

Normally, for classes with a parameterless constructor, I would just do this:

开发者_Python百科For<IMyClass>().Use<MyClass>();

But how would I do it if MyClass had one constructor ?

public class MyClass : IMyClass
{
    public MyClass(string name, string etc)
    {

    }
}


If the values you want to pass is known at registration time you can go with this:

For<IMyClass>().Use<MyClass>()
  .Ctor<string>("name").Is("theName")
  .Ctor<string>("etc").Is("etcetera");


This worked for me

public interface IMyClass
{
    string MyMethod();
}

public class MyClass : IMyClass
{
    private readonly string myName;
    private readonly string myEtc;

    public MyClass(string name, string etc)
    {
        myName = name;
        myEtc = etc;
    }

   public string MyMethod()
   {
       return myName + myEtc;
   }
}

public class FactoryTest
{
    public string GetMyString()
    {
        RegisterMyClass();
        return ObjectFactory.GetInstance<IMyClass>().MyMethod();
    }

    public void RegisterMyClass()
    {
        ObjectFactory.Initialize(
              f => f.For<IMyClass>().Use(x => new MyClass("a", "b")));
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜