0

我是一名 Java 开发人员,被迫学习 C#。由于我无法忍受不使用依赖注入容器,我正在尝试在我的项目中配置 Spring.NET。

我的项目在 Visual Studio 中分为两个解决方案:一个用于我所有业务逻辑、服务、DAO 等的 ClassLibrary 解决方案,以及一个 Webapp 部分(ASP.NET 页面等)。

我发现有趣的是,我可以通过代码隐藏将依赖项有效地注入到实际页面中,而 JSP 无法做到这一点。但是,我想要的是从 ClassLibrary 解决方案将服务 (UserService) 注入到 Webapp 部分中的 Login.aspx.cs 中。

我是否必须在 ClassLibrary 端和 Web.Config 端的 App.Config 中定义 UserService 对象?

4

2 回答 2

1

不可以。您可以使用“程序集”前缀(类似于 Java 中的“类路径”前缀)将 Spring.Net 配置从 DLL 项目(定义 UserService)导入到 Web 项目中。然后,在您的 Web 项目的 spring 配置中,您可以引用 DLL 中定义的所有对象。

不要忘记将包含配置(在 DLL 项目中)的 XML 文件标记为要包含在 DLL 中的资源。

于 2009-12-16T14:32:41.210 回答
0

运行 ASP.NET 应用程序时,未使用类库的 app.config。仅考虑 Web 应用程序的 web.config。因此,在您的 web.config 中,您可以声明依赖项:

<configSections>
    <sectionGroup name="spring">
        <section name="context" 
                 type="Spring.Context.Support.ContextHandler, Spring.Core"/>
    </sectionGroup>
</configSections>
<spring>
    <context>
        <resource uri="~/Config/context.xml"/>
    </context>
</spring>

在 context.xml 中:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net">
    <!-- Define the UserService object -->
    <object id="userService" type="Namespace.UserService, ClassLibrary" />
</objects>

最后在你的代码后面:

var userService = (UserService)ContextRegistry
    .GetContext()
    .GetObject("userService");
于 2009-12-16T14:35:24.043 回答