C# MEF防止手动安装类
我想知道我是否可以阻止手动创建类?我想确定它是进口的C# MEF防止手动安装类,c#,.net,mef,C#,.net,Mef,我想知道我是否可以阻止手动创建类?我想确定它是进口的 [Export] [PartCreationPolicy(CreationPolicy.Shared)] public class TwoWayMessageHubService { [ImportingConstructor] public TwoWayMessageHubService(ILoggerService loggerService) { } } 因此,我想确保这是可行的: [Import] p
[Export]
[PartCreationPolicy(CreationPolicy.Shared)]
public class TwoWayMessageHubService
{
[ImportingConstructor]
public TwoWayMessageHubService(ILoggerService loggerService)
{
}
}
因此,我想确保这是可行的:
[Import]
public TwoWayMessageHubService MHS {get; set;)
并确保这不会:
var MHS = new TwoWayMessageHubService(logger);
事实上,这是可能的。只需将[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; }
}
使用导出装饰的记录器
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),则会注意到它没有编译
希望这有助于解决问题,但如果您将构造函数标记为
[过时]
,并使FxCop/StyleCop(不记得是哪个)在使用过时的
字段/方法时抛出编译错误呢?为什么要故意破坏代码?太好了!只需确保未使用默认构造函数,private TwoWayMessageHubService(){}
,然后一切正常