使用 Structuremap 使用委托类型构造函数参数注册和解析服务
Registering and Resolving a Service with delegate type constructor parameter using Structuremap
我有以下服务class:
public class MyService : IService
{
public MyService(Func<string,bool> question)
{
....
}
...
}
当我在我的 WinForms 应用程序中使用此服务时,我想将以下代码作为 MyService
构造函数参数
(string question) =>
{
var questionForm = new SimpleQuestionForm(question);
if(questionForm.ShowDialog() == DialogResult.OK)
return true;
else
return false;
}
我如何告诉 StructureMap 我的 question
代表是什么?
我在我的 WindowsForm 项目中定义了以下注册表 class:
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);
}
}
然后按照项目 Program.cs
开头的代码将注册表添加到 ObjectFactory 的容器中:
ObjectFactory.Container.Configure(x=>x.IncludeRegistry<WinUIRegistry>());
重新分配:
var service = ObjectFactory.Container.GetInstance<IService>();
我有以下服务class:
public class MyService : IService
{
public MyService(Func<string,bool> question)
{
....
}
...
}
当我在我的 WinForms 应用程序中使用此服务时,我想将以下代码作为 MyService
构造函数参数
(string question) =>
{
var questionForm = new SimpleQuestionForm(question);
if(questionForm.ShowDialog() == DialogResult.OK)
return true;
else
return false;
}
我如何告诉 StructureMap 我的 question
代表是什么?
我在我的 WindowsForm 项目中定义了以下注册表 class:
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);
}
}
然后按照项目 Program.cs
开头的代码将注册表添加到 ObjectFactory 的容器中:
ObjectFactory.Container.Configure(x=>x.IncludeRegistry<WinUIRegistry>());
重新分配:
var service = ObjectFactory.Container.GetInstance<IService>();