MEF防止类被手动设置

时间:2017-07-12 18:58:09

标签: c# .net mef

我想知道我是否能以某种方式阻止手动创建类?我想确保它只是导入。

[Export]
[PartCreationPolicy(CreationPolicy.Shared)]
public class TwoWayMessageHubService
{
    [ImportingConstructor]
    public TwoWayMessageHubService(ILoggerService loggerService)
    {
    }
}

所以,我想确保这个有效:

[Import]
public TwoWayMessageHubService MHS {get; set;)

并确保不会:

var MHS = new TwoWayMessageHubService(logger);

1 个答案:

答案 0 :(得分:1)

事实上这是可能的。只需将 [Import] 属性应用于构造函数的参数,并使构造函数保持私有。我根据您的代码制作了以下示例,它可以运行,您可以对其进行测试。

首先, TwoMessageHubService 包含我提到的更改:

[Export]
    [PartCreationPolicy(CreationPolicy.Shared)]
    public class TwoWayMessageHubService
    {
        [ImportingConstructor]
        private TwoWayMessageHubService([Import]ILogger logger) { }
    }

请注意,构造函数是私有

然后一个必须用TwoWayMessageHubService实例组成的类:

public class Implementer
    {
        [Import]
        public TwoWayMessageHubService MHS { get; set; }
    }

Logger用导出

装饰
   public interface ILogger { }

    [Export(typeof(ILogger))]
    public class Logger : ILogger { }

主要:

var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            var container = new CompositionContainer(catalog);

            var implementer = new Implementer();
            container.ComposeParts(implementer);
            //var IdoNotCompile = new TwoWayMessageHubService(new Logger());

            Console.ReadLine();

如果您取消注释评论(lol),那么您会注意到它没有编译。

希望这有帮助

相关问题