我一直在寻找WebApi属性的非参数注入选项.
我的问题是使用Structuremap是否真的可以实现这一点?
我一直在谷歌搜索,但继续提出属性注入(我不喜欢使用)或假设的构造函数注入的实现,我到目前为止无法复制.
我选择的容器是Structuremap,但是任何这样的例子就足够了,因为我能够转换它.
有人管过这个吗?
structuremap dependency-injection custom-attributes asp.net-web-api structuremap3
我现在正试图弄清楚结构图,因为ObjectFactory静态函数已被标记为过时.
从长远来看,我必须在MVC和WebApi应用程序中使用它.以前使用时,在global.asax中放置一行到静态方法,以使用ObjectFactory初始化所有内容.
ObjectFactory.Initialize{
container.For .....
}
Run Code Online (Sandbox Code Playgroud)
试图将其转换为新的IContainer方法我已经提出以下内容但是我想知道我是否实际上无意中在我的方法中实现了这个经常提到的反模式.
返回容器的静态方法:
public class StructureMapConfig
{
public static IContainer GetContainer()
{
return new Container(container =>
{
container.For<IUserService>().Use<UserService>();
container.For<IStringService>().Use<StringService>();
container.For<IUserRepository>().Use<UserRepository>();
});
}
}
Run Code Online (Sandbox Code Playgroud)
Userservice的contstructor看起来像这样:
public class UserService : IUserService
{
private readonly IUserRepository _userRepository;
private readonly IStringService _stringService;
public UserService(IUserRepository userRepository, IStringService stringService)
{
_userRepository = userRepository;
_stringService = stringService;
}
Run Code Online (Sandbox Code Playgroud)
最后,初始化(在控制台应用程序中的这个实例)看起来像这样:
private static IUserService _userService;
private static IContainer _container;
static void Main(string[] args)
{
_container = StructureMapConfig.GetContainer();
_userService = _container.GetInstance<IUserService>();
}
Run Code Online (Sandbox Code Playgroud)
所以对我的问题.
继我之前关于如何在结构图中实现IContainer的帖子之后,我已经打了一段时间我希望是我的最后一个问题了.
如何将其他(非结构图注入)对象传递给构造函数?
让我们从我用来测试这些东西的示例控制台应用程序中获取以下内容.
static void Main(string[] args)
{
_container = StructureMapConfig.GetContainer();
_userService = _container.GetInstance<IUserService>();
}
Run Code Online (Sandbox Code Playgroud)
抛出以下错误,因为我的构造函数有randomParam,而structuremap不知道如何填补空白:
StructureMap.dll中发生了一个未处理的"StructureMap.StructureMapBuildPlanException"类型异常
附加信息:无法为具体类型CommonServices.UserService创建构建计划
构造函数:
public UserService(IUserRepository userRepository, IStringService stringService, string randomParam)
{
_userRepository = userRepository;
_stringService = stringService;
}
Run Code Online (Sandbox Code Playgroud)
在我的注册表中,我定义了我的用户服务:
this.For<IUserService>().Use<UserService>();
Run Code Online (Sandbox Code Playgroud)
我的问题是如何以最简单的方式做到这一点?
我找到了这个链接,但看不到如何使用这些建议,因为我必须让我的调用类知道UserService的依赖关系.您可以看到其中一些是数据层项目,我不想告诉我的UI层有关它们.
http://structuremap.github.io/resolving/passing-arguments-at-runtime/