Registering and Resolving a Service with delegate type constructor parameter using Structuremap

167 Views Asked by At

I have following service class:

public class MyService : IService
{
   public MyService(Func<string,bool> question)
   {
      ....
   }
   ...
}

When I use this service in my WinForms application I want to pass following code as MyService constructor parameter

(string question) => 
{ 
   var questionForm = new SimpleQuestionForm(question);
   if(questionForm.ShowDialog() == DialogResult.OK)
      return true;
   else
      return false; 
}

How can I tell to the StructureMap that what is my question delegate?

1

There are 1 best solutions below

0
Masoud On BEST ANSWER

I defined following Registry class in my WindowsForm project:

public class WinUIRegistry:Registry
{
    public WinUIRegistry()
    {
        bool SimpleQuestionDelegate(string question)
        {
            var questionForm = new SimpleQuestionForm();
            questionForm.SetData(question);
            return questionForm.ShowDialog() == DialogResult.Yes;
        }

        For<IService>()
            .Use<MyService>()
            .Ctor<Func<string, bool>>().Is(SimpleQuestionDelegate);
    }
}

And then added registry to the ObjectFactory's Container by following code in the start of the project's Program.cs:

ObjectFactory.Container.Configure(x=>x.IncludeRegistry<WinUIRegistry>()); 

For relosving:

var service = ObjectFactory.Container.GetInstance<IService>();