6

介绍

SessionModel是一个提供多种服务的服务定位器(我以后会详细阐述我的系统架构,但现在我需要这样做)。

代码

我将以下代码部分编辑为简短、自包含、正确(可编译)、示例(SSCCE):

using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var sessionModel = new SessionModel(3);

            // first case (see text down below):
            var compositionContainer = new CompositionContainer();

            // second case (see text down below):
            //var typeCatalog = new TypeCatalog(typeof (SessionModel));
            //var compositionContainer = new CompositionContainer(typeCatalog);

            compositionContainer.ComposeExportedValue(sessionModel);

            var someService = compositionContainer.GetExportedValue<ISomeService>();
            someService.DoSomething();
        }
    }

    public class SessionModel
    {
        private int AValue { get; set; }

        [Export]
        public ISomeService SomeService { get; private set; }

        public SessionModel(int aValue)
        {
            AValue = aValue;
            // of course, there is much more to do here in reality:
            SomeService = new SomeService();
        }
    }

    public interface ISomeService
    {
        void DoSomething();
    }

    public class SomeService : ISomeService
    {
        public void DoSomething()
        {
            Console.WriteLine("DoSomething called");
        }
    }
}

问题

我希望 MEFSomeService在组成其他部分时考虑服务定位器导出的部分(即),但不幸的是,这不起作用。

第一个案例

当我尝试获取导出的值时,ISomeServiceSystem.ComponentModel.Composition.ImportCardinalityMismatchException告诉我没有具有此合同名称和所需类型标识 ( ConsoleApplication1.ISomeService) 的导出。

第二种情况

如果我CompositionContainer使用TypeCatalog异常创建,则略有不同。这是一个System.ComponentModel.Composition.CompositionException告诉我 MEF 没有找到创建方法的方法ConsoleApplication1.SessionModel(这是正确的,也是我自己做的原因)。

附加信息

mefx说两种情况:

[Part] ConsoleApplication1.SessionModel from: DirectoryCatalog (Path=".")
  [Export] ConsoleApplication1.SessionModel.SomeService (ContractName="ConsoleApplication1.ISomeService")

[Part] ConsoleApplication1.SessionModel from: AssemblyCatalog (Assembly="ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")
  [Export] ConsoleApplication1.SessionModel.SomeService (ContractName="ConsoleApplication1.ISomeService")

我需要做什么?这是否可以使用 MEF 或我必须使用 Unity 或 StructureMap 或其他东西?这可以实现ExportProvider吗?

4

4 回答 4

1

好的,我就是这样做的:

我在我的(见下面的代码)中实现了我自己的SessionModelExportProvider查找导出。SessionModelSessionModelExport仅用于保存导出数据,而不是创建服务实例,而是返回SessionModel.

public class SessionModelExportProvider : ExportProvider
{
    private List<Export> Exports { get; set; }

    public SessionModelExportProvider(SessionModel sessionModel)
    {
        // get all the properties of the session model having an Export attribute
        var typeOfSessionModel = typeof (SessionModel);
        PropertyInfo[] properties = typeOfSessionModel.GetProperties();
        var propertiesHavingAnExportAttribute =
            from p in properties
            let exportAttributes = p.GetCustomAttributes(typeof (ExportAttribute), false)
            where exportAttributes.Length > 0
            select new
                       {
                           PropertyInfo = p,
                           ExportAttributes = exportAttributes
                       };

        // creating Export objects for each export
        var exports = new List<Export>();
        foreach (var propertyHavingAnExportAttribute in propertiesHavingAnExportAttribute)
        {
            var propertyInfo = propertyHavingAnExportAttribute.PropertyInfo;
            foreach (ExportAttribute exportAttribute in propertyHavingAnExportAttribute.ExportAttributes)
            {
                string contractName = exportAttribute.ContractName;
                if (string.IsNullOrEmpty(contractName))
                {
                    Type contractType = exportAttribute.ContractType ?? propertyInfo.PropertyType;
                    contractName = contractType.FullName;
                }

                var metadata = new Dictionary<string, object>
                                   {
                                       {CompositionConstants.ExportTypeIdentityMetadataName, contractName},
                                       {CompositionConstants.PartCreationPolicyMetadataName, CreationPolicy.Shared}
                                   };
                var exportDefinition = new ExportDefinition(contractName, metadata);
                var export = new SessionModelExport(sessionModel, propertyInfo, exportDefinition);
                exports.Add(export);
            }
        }

        Exports = exports;
    }

    protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition,
                                                          AtomicComposition atomicComposition)
    {
        return Exports.Where(e => definition.IsConstraintSatisfiedBy(e.Definition));
    }
}

public class SessionModelExport : Export
{
    private readonly SessionModel sessionModel;
    private readonly PropertyInfo propertyInfo;
    private readonly ExportDefinition definition;

    public SessionModelExport(SessionModel sessionModel, PropertyInfo propertyInfo, ExportDefinition definition)
    {
        this.sessionModel = sessionModel;
        this.propertyInfo = propertyInfo;
        this.definition = definition;
    }

    public override ExportDefinition Definition
    {
        get { return definition; }
    }

    protected override object GetExportedValueCore()
    {
        var value = propertyInfo.GetValue(sessionModel, null);
        return value;
    }
}
于 2013-09-04T10:08:26.090 回答
0

问题是 SomeService 是一个实例属性。您的系统中可能有多个 SessionModel 对象,而 MEF 无法知道哪个 SessionModel 正在返回应该与导入匹配的 ISomeService 实例。

相反,只需将 SessionModel 设为静态类,将 SomeService 设为静态属性即可。或者,使 SessionModel 成为单例。SomeService 属性仍然是静态的,但会从唯一的 SessionModel 实例中导出服务。

于 2013-08-06T21:20:50.760 回答
0
using System;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.ReflectionModel;
using System.Reflection;
using System.Linq;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {

            var catalogs = new AggregateCatalog();
            var catalog = new System.ComponentModel.Composition.Hosting.AssemblyCatalog(Assembly.GetExecutingAssembly());
            catalogs.Catalogs.Add(catalog);
            var sessionModel = new SessionModel(3);
            var container = new CompositionContainer(catalog); 
            ISomeService someService = container.GetExportedValueOrDefault<ISomeService>(sessionModel.cname);
            if (someService != null)
            {
                someService.DoSomething();
            }
        }
    }

    public class SessionModel
    {
        private int AValue { get; set; }

        //[Import("One",typeof(ISomeService))]
        //public ISomeService SomeService { get; private set; }

        public SessionModel(int aValue)
        {
            AValue = aValue;
            // of course, there is much more to do here in reality:
        }

        public string cname { get { return "One"; } }
    }

    public class SessionModel1
    {
        private int AValue { get; set; }

        //[Import("Two",typeof(ISomeService))]
        //public ISomeService SomeService { get; private set; }

        public SessionModel1(int aValue)
        {
            AValue = aValue;
        }
        public string cname { get { return "Two"; } }

    }

    public interface ISomeService
    {
        void DoSomething();
    }

    [Export("One",typeof(ISomeService))]
    public class SomeService : ISomeService
    {
        public SomeService()
        {
            Console.WriteLine("Some Service Called");
        }
        public void DoSomething()
        {
            Console.WriteLine("DoSomething called");
            Console.ReadKey();
        }
    }

    [Export("Two",typeof(ISomeService))]
    public class SomeService1 : ISomeService
    {
         public SomeService1()
        {
            Console.WriteLine("Some Service1 Called");
        }
        public void DoSomething()
        {
            Console.WriteLine("DoSomething called 1");
            Console.ReadKey();
        }
    }
}
于 2013-08-08T23:27:19.903 回答
0

第一种情况:通过传递sessionModelComposeExportedValue您添加 type 的一部分SessionModel而不是ISomeService. 要使这种情况有效,您需要将服务传递给 ComposeExportedValue。

compositionContainer.ComposeExportedValue(sessionModel.SomeService);

第二种情况:在这种情况下,您将零件的创建留给容器。如果存在无参数构造函数或带有使用ImportingConstructorAttribute修饰的参数的构造函数,则容器可以创建新部件。这很可能意味着您需要稍微更改您的设计。

就我个人而言,我会选择第一种情况,但尽量减少这种情况。毕竟,MEF 的所有正常(和建议)用法是让容器创建和处理部件。

于 2013-08-21T07:25:04.537 回答