对于具有单个应用程序的解决方案,一般建议是在应用程序项目(您的 Web 应用程序或 Web 服务项目)中注册您的容器。对于 Web 应用程序,这通常是 Global.asax Application_Start
。这个将所有东西连接在一起的地方在 DI 术语中称为合成根。
使用多应用程序解决方案,每个应用程序项目仍然有一个组合根。这是必须的,因为每个应用程序都有其独特的配置。另一方面,重复的代码总是不好的。当你引入一个新的抽象时,你不想改变三个地方。
诀窍是将所有注册移到项目层次结构中。例如,您可以定义一个依赖于您的业务层程序集(及以下)的“引导程序集”,并让它拥有那些不会更改的程序集的所有注册。然后应用程序的组合根可以使用该程序集来获取默认注册并使用应用程序特定的依赖项对其进行扩展。
这样的事情可能看起来像这样:
// MVC Composition root
public static void Bootstrap()
{
var container = new Container();
// Default registrations
BusinessLayerBootstrapper.Bootstrap(container);
// Application specific registrations
container.Bind<IUserContext>().To<AspNetUserContext>();
DependencyResolver.Current =
new ContainerDependencyResolver(container);
}
// Windows Service Composition root
public static void Bootstrap()
{
var container = new Container();
// Default registrations
BusinessLayerBootstrapper.Bootstrap(container);
// Application specific registrations
container.Bind<IUserContext>().To<SystemUserContext>()
.SingleScoped();
// Store somewhere.
Bootstrapper.Container = container;
}
// In the BL bootstrap assembly
public static class BusinessLayerBootstrapper
{
public static void Bootstrap(Container container)
{
container.Bind<IDepenency>().To<RealThing>();
// etc
}
}
尽管您不需要单独的引导程序程序集(您可以将此代码放在 BL 本身中),但这使您可以使业务层程序集免受容器的任何依赖。
另请注意,我只是调用静态Bootstrap()
方法,而不是使用 (Ninject) 模块。我试图让我的答案独立于框架,因为您的问题是一般性的,并且所有 DI 框架的建议都是相同的。但是,如果您愿意,当然可以使用 Ninject 模块功能。