Unity应用程序块,如何参数传递给注塑厂? [英] Unity Application Block, How pass a parameter to Injection Factory?
问题描述
在这里,我有什么现在
Container.RegisterType<IUserManager, UserManagerMock>();
Container.RegisterType<IUser, UserMock>(
new InjectionFactory(
(c) => c.Resolve<IUserManager>().GetUser("John")));
和得到它
Container.Resolve<IProfile>();
我想通过一个名称作为参数传递给工厂,这样我就能够解决用户对象,名称;
事情是这样的:
I want to pass a name as parameter to Factory so that I will be able to resolve user object with name; Something like this:
Container.Resolve<IProfile>("Jonh");
我怎样才能改变这种情况的类型注册?
How can I change the type registration for this case?
推荐答案
虽然大多数DI框架,拥有先进的功能,做这些类型的注册,我个人而改变我的应用程序的设计来解决这样的问题。这使我的DI配置简单,使代码更容易理解。特别是对于创建依赖于一些上下文中的对象(线程,要求,等等)或者必须明确管理的一生中,我喜欢定义工厂。工厂让这些事情变得更加明确。
While most DI frameworks have advanced features to do these types of registrations, I personally rather change the design of my application to solve such a problem. This keeps my DI configuration simple and makes the code easier to understand. Especially for the creation of objects that depend on some context (thread, request, whatever) or have a lifetime that must be managed explicitly, I like to define factories. Factories make these things much more explicit.
在您的情况,您要为某个用户读取配置文件。这是典型的东西,你想有一个工厂。这里有这样一个例子:
In your situation, you want to fetch a profile for a certain user. This is typically something you would like to have a factory for. Here's an example of this:
// Definition
public interface IProfileFactory
{
IProfile CreateProfileForUser(string username);
}
// Usage
var profile = Container.Resolve<IProfileFactory>()
.CreateProfileForUser("John");
// Registration
Container.RegisterType<IProfileFactory, ProfileFactory>();
// Mock implementation
public class ProfileFactory : IProfileFactory
{
public IProfile CreateProfileForUser(string username)
{
IUser user = Container.Resolve<IUserManager>()
.GetUser(username);
return new UserProfile(user);
}
}
我希望这有助于。
I hope this helps.
这篇关于Unity应用程序块,如何参数传递给注塑厂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!