以下测试表明MEF在必须之前不会实例化服务。 (在这种情况下,我只是查询元数据)
[TestMethod]
public void Mef_DoesNotInstantiateService_WhenOnlyQueryingForMetadata()
{
var aggregateCatalog = CreateMefCatalog();
var container = new CompositionContainer(aggregateCatalog, true);
var serviceConsumer = container.GetExportedValue<ServiceConsumer>();
serviceConsumer.Services.Any(x => x.Metadata.Name == "Service1").Should().BeTrue();
}
以下测试失败,因为Autfac正在尝试创建Service1的实例 - 它在构造函数中抛出异常。
[TestMethod]
public void Autofac_DoesNotInstantiateService_WhenOnlyQueryingForMetadata()
{
var aggregateCatalog = CreateMefCatalog();
var builder = new ContainerBuilder();
builder.RegisterComposablePartCatalog(aggregateCatalog);
var container = builder.Build();
//Next line will throw an exception. (Autofac is instantiating the service, but should not)
var serviceConsumer = container.Resolve<ServiceConsumer>();
//Note: This test will never get here..
serviceConsumer.Services.Any(x => x.Metadata.Name == "Service1").Should().BeTrue();
}
测试所需的其他代码
static AggregateCatalog CreateMefCatalog()
{
return new AggregateCatalog(new List<ComposablePartCatalog>
{
new AssemblyCatalog(Assembly.GetExecutingAssembly())
});
}
[Export]
class ServiceConsumer
{
[ImportMany]
public IEnumerable<Lazy<IService, INameMetadata>> Services { get; set; }
}
public interface IService { }
[Export(typeof (IService))]
[ExportMetadata("Name", "Service1")]
public class Service1 : IService
{
public Service1()
{
throw new Exception("This service should never be created");
}
}
public interface INameMetadata
{
string Name { get; }
}
BTW:我使用的是目前稳定版本:Autofac 3.5.2和Autofac.Mef 3.0.3