我同意@stakx 评估。我使用不同的方法来创建容器,以使其与环境更加无关。我创建一个界面:
/// <summary>
/// Defines the required contract for implementing a composition container factory.
/// </summary>
public interface ICompositionContainerFactory
{
#region Methods
/// <summary>
/// Creates an instance of <see cref="CompositionContainer"/>.
/// </summary>
/// <returns>An instance of <see cref="CompositionContainer"/>.</returns>
CompositionContainer CreateCompositionContainer();
#endregion
}
使用默认实现(适用于控制台应用程序、服务主机):
public class DefaultCompositionContainerFactory : ICompositionContainerFactory
{
#region Methods
/// <summary>
/// Creates an instance of <see cref="CompositionContainer"/>.
/// </summary>
/// <returns>
/// An instance of <see cref="CompositionContainer"/>.
/// </returns>
public CompositionContainer CreateCompositionContainer()
{
var domain = AppDomain.CurrentDomain;
string path = domain.BaseDirectory;
// Use the base directory from where the application is running.
var catalog = new DirectoryCatalog(path);
// Create the container.
var container = new CompositionContainer(catalog);
return container;
}
#endregion
}
以及特定于Web的实现:
public class WebCompositionContainerFactory : ICompositionContainerFactory
{
#region Methods
/// <summary>
/// Creates an instance of <see cref="CompositionContainer"/>.
/// </summary>
/// <returns>
/// An instance of <see cref="CompositionContainer"/>.
/// </returns>
public CompositionContainer CreateCompositionContainer()
{
string path = HttpRuntime.BinDirectory;
// Use the base directory from where the application is running.
var catalog = new DirectoryCatalog(path);
// Create the container.
var container = new CompositionContainer(catalog);
return container;
}
#endregion
}
我通过配置连接起来。
要考虑的另一件事是您将 *.exe 作为目录过滤器传递,您是否在 Web 应用程序中使用可执行程序集?