如何使用静态工厂方法创建对象?

时间:2011-09-27 23:26:44

标签: c# unity-container

我知道Unity可以配置为使用类的构造函数来创建类的实例(如下所示),但这不是我想要的。

container.RegisterType<IAuthoringRepository, AuthoringRepository>();

我想将Unity配置为使用工厂方法,在解析RepositoryFactory.CreateAuthoringRepository(WindowsIdentity.GetCurrent())类型时,将windows身份作为参数传递(即:IAuthoringRepository)。我该怎么做?

2 个答案:

答案 0 :(得分:49)

一种方法是让RepositoryFactory实现IRepositoryFactory,然后注册它。已解析的类型可以获取工厂,然后调用其CreateAuthoringRepository方法。如果需要,您可以创建一个名为CreateAuthoringRepositoryForCurrentIdentity的重载,或者使用Unity注册工厂的IIdentity依赖项。

我可能只是注入一个工厂并保留CreateAuthoringRepository方法,然后让客户端通过WindowsIdentity.GetCurrent()。这样,身份总是很新鲜,你可以嘲笑工厂进行测试。

或者,您可以使用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

这适用于Unity 2.0。对于早期版本,请参阅StaticFactoryExtension

答案 1 :(得分:0)

现在方法InjectionFactory已过时。这就是为什么最好使用方法RegisterFactory的原因。在下面,我显示了先前的代码如何更改。您如何看待,我更改了CreateAuthoringRepository方法。现在,它是带有一个参数 IUnityContainer容器

static 方法
void Main()
{
    using (var container = new UnityContainer())
    {
        container.RegisterFactory<IAuthoringRepository>(CreateAuthoringRepository);

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

public static IAuthoringRepository CreateAuthoringRepository(IUnityContainer container)
{
    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; }
}