我正熟悉C#IoC框架。我选择了StructureMap.Webapi2来集成到现有的api中。 我有以下场景,我不确定最好的实现方式是什么。
public class MyController : ApiController
{
public IHttpActionResult MyAction(string clientCode, [FromBody]MyDto bodyData)
{
var client = new ClientManager().GetClientByCode(clientCode);
var someData = new SomeData
{
User = bodyData.User,
ClientCode = clientCode,
SomeField = client.SomeField
};
var myService = new WorkerService(someData);
myService.DoSomething();
return Ok();
}
}
查看WorkerService:
public WorkerService(SomeData someData)
{
_someData = someData;
_someCollection = GetSomeData(); // GetSomeData uses _someData
}
public DoSomething()
{
// some code that uses _someData and _someCollection
}
方法1:
行动将如下:
public IHttpActionResult MyAction(string clientCode, [FromBody]MyDto bodyData)
{
var client = _clientManager.GetClientByCode(clientCode);
var someData = new SomeData
{
User = bodyData.User,
ClientCode = clientCode,
SomeField = client.SomeField
};
_myService.SomeData = someData;
_myService.DoSomething();
return Ok();
}
方法2(我不确定如何实施)
对我来说,方法1似乎更快更简单,但方法2似乎更具吸引力,更具挑战性,并且有更多的学习。
答案 0 :(得分:0)
我最终找到了解决问题的方法:
对于我在SomeData对象中需要的其余数据,我按照方法1,使WorkerService的构造函数无参数并传递数据,如:
_myService.DoSomething(someData);
最后一招是将ActionFilter添加到config.Filters,因为我的过滤器有自己的依赖项,我不能这样做:
config.Filters.add(new MyActionFilter(What_About_The_Parametes_???))
我必须获取structureMap的容器实例并让它返回我的过滤器的一个实例,这将导致所有依赖项被注入其中,然后我可以将过滤器实例添加到config.Filters:
var container = StructuremapMvc.StructureMapDependencyScope.Container;
config.Filters.Add(container.GetInstance<IMyActionFilter>());