在您的代码周围提供导入

时间:2008-10-13 19:17:06

标签: c# design-patterns mef

在我MEF的用法中,我想要在我的代码的许多其他部分提供一些导入。类似的东西:

[Export (typeof (IBarProvider))]
class MyBarFactory : IBarPovider
{
    [Import]
    public IFoo1Service IFoo1Service { get; set; }

    [Import]
    public IFoo2Service IFoo2Service { get; set; }

    [Import]
    public IFoo3Service IFoo3Service { get; set; }

    [Import]
    public IFoo4Service IFoo4Service { get; set; }

    [Import]
    public IFoo5Service IFoo5Service { get; set; }

    public IBar CreateBar()
    {
        return new BarImplementation(/* want to pass the imported services here */);
    }
}

class BarImplementation : IBar
{
    readonly zib zib;

    public BarImplementation(/* ... */)
    {
        this.zib = new Zib(/* pass services here, too */);
    }
}

我可以将每个导入的服务作为单个参数传递,但它是很多无聊的代码。必须有更好的东西。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

我不完全确定这会回答你的问题,但是你考虑过使用构造函数注入吗?

class BarImplementation : IBar
{
    [ImportingConstructor]
    public BarImplementation(IFoo1Service foo1, IFoo2Service foo2, ...) { }
}

通过使用ImportingConstructor属性标记构造函数,它将基本上使该构造函数的所有参数都需要导入。

答案 1 :(得分:0)

我考虑过制作一个提供这些服务的界面:

partial class BarImplementation
{
    public IRequiredServices
    {

        public IFoo1Service IFoo1Service { get; set; }
        public IFoo2Service IFoo2Service { get; set; }  
        public IFoo3Service IFoo3Service { get; set; }          
        public IFoo4Service IFoo4Service { get; set; }      
        public IFoo5Service IFoo5Service { get; set; }
    }
}

然后MyBarFactory实施BarImplementation : BarImplementation.IRequiredServices。这很容易写,但是,如何将它们传递给Zib?我不希望以这种方式将Zib与其消费者结合。

答案 2 :(得分:0)

我可以使IImports包含我导入的所有服务的接口,在任何地方传递它,然后类可以使用或不使用他们喜欢的任何一个。但是,所有的课程都是完美的。

相关问题