如何使用静态工厂方法来创建对象呢? [英] How to create objects using a static factory method?

查看:304
本文介绍了如何使用静态工厂方法来创建对象呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,团结可以被配置为使用一个类的构造函数来创建类的实例(如下面),但是这不是我想要的。

I know Unity can be configured to use a class' constructor to create an instance of a class (like below) but that's not what I want.

container.RegisterType<IAuthoringRepository, AuthoringRepository>();



我想统一配置使用工厂方法作为参数传递的Windows标识(即:RepositoryFactory.CreateAuthoringRepository(WindowsIdentity.GetCurrent())解析式IAuthoringRepository的时)。我该怎么做呢?

I would like to configure Unity to use a factory method with the windows identity passed as a parameter (ie: RepositoryFactory.CreateAuthoringRepository(WindowsIdentity.GetCurrent())) when resolving a type of IAuthoringRepository. How do i do this?

推荐答案

的一种方法是有RepositoryFactory实施IRepositoryFactory,然后注册了。解决的类型可以得到一个工厂,然后调用其CreateAuthoringRepository方法。如果需要,您可以创建一个名为CreateAuthoringRepositoryForCurrentIdentity过载,或注册在出厂时统一的IIdentity的依赖关系。

One way is to have RepositoryFactory implement IRepositoryFactory, then register that. Resolved types can get a factory, then call its CreateAuthoringRepository method. You could create an overload called CreateAuthoringRepositoryForCurrentIdentity if desired, or register an IIdentity dependency of the factory with Unity.

我大概只是​​注入的工厂并离开CreateAuthoringRepository方法你拥有了它,然后让​​客户通过WindowsIdentity.GetCurrent()。 。这样的身份永远是新鲜的,你可以模拟工厂进行测试

I'd probably just inject a factory and leave the CreateAuthoringRepository method as you have it, then have the clients pass WindowsIdentity.GetCurrent(). That way the identity is always fresh, and you can mock the factory for testing.

另外,你可以用InjectionFactory指定一个委托:

Alternately, you can specify a delegate with InjectionFactory:

void Main()
{
    using (var container = new UnityContainer())
    {
        container.RegisterType<IAuthoringRepository>(
            new InjectionFactory(c => CreateAuthoringRepository()));

        Console.WriteLine("debug - resolving model");
        var model = container.Resolve<Model>();
    }
}

public IAuthoringRepository CreateAuthoringRepository()
{
    Console.WriteLine("debug - calling factory");
    return new AuthoringRepository
        { Identity = WindowsIdentity.GetCurrent() };
}

public class Model
{
    public Model(IAuthoringRepository repository)
    {
        Console.WriteLine(
            "Constructing model with repository identity of "
            + repository.Identity);
    }
}

public interface IAuthoringRepository
{
    IIdentity Identity { get; }
}

public class AuthoringRepository : IAuthoringRepository
{
    public IIdentity Identity { get; set; }
}

这将显示:

debug - resolving model
debug - calling factory
Constructing model with repository identity of System.Security.Principal.WindowsIdentity



模式的构建

这对统一2.0。与早期版本,请参见 StaticFactoryExtension

这篇关于如何使用静态工厂方法来创建对象呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆