无法使弹簧依赖注入在简单的Web应用程序上工作

时间:2016-02-20 00:15:54

标签: c# asp.net dependency-injection web-config spring.net

经过多方努力,我无法在我的应用程序和业务层之间创建一个简单的DI示例。

以下是我的web.config中的spring片段:

<configSections>
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web"/>
      <section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core"/>
      <section name="parsers" type="Spring.Context.Support.NamespaceParsersSectionHandler, Spring.Core"/>
    </sectionGroup>
</configSections>
<spring>
    <parsers>
        <parser type="Spring.Data.Config.DatabaseNamespaceParser, Spring.Data"/>
        <parser type="Spring.Transaction.Config.TxNamespaceParser, Spring.Data"/>
    </parsers>
    <context>
        <resource uri="config://spring/objects"/>
        <resource uri="~/BusinessLayer/Business.xml"/>
        <resource uri="~/Web.xml"/>
    </context>
    <objects xmlns="http://www.springframework.net"     xmlns:db="http://www.springframework.net/database"     xmlns:tx="http://www.springframework.net/tx">
    <!-- Pages -->
    </objects>
</spring>

这是Business.xml

<?xml version="1.0" encoding="utf-8" ?>
    <objects xmlns="http://www.springframework.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd">
  <object id="UserBLL" type="Kupla.BusinessLayer.UserBLL, Kupla.BusinessLayer">
  </object>
</objects>

这是Web.xml:

<?xml version="1.0" encoding="utf-8" ?>
<objects xmlns="http://www.springframework.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd">

  <object type="default.aspx">
    <property name="UserBLL" ref="UserBLL"></property>
  </object>

</objects>

这是业务层中UserBLL.cs的定义:

namespace Kupla.BusinessLayer
{
    class UserBLL : IUserBLL
    {
        public int TestGetUserId()
        {
            int userId = 1;
            return userId;
        }
    }
}

最后,应用程序层中的代码试图从default.aspx.cs访问业务层:

using System;
using Kupla.BusinessLayer;

namespace Kupla
{
    public partial class _default : System.Web.UI.Page
    {
        private IUserBLL _userBLL;
        public IUserBLL UserBLL
        {
            set { _userBLL = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            int userID = _userBLL.TestGetUserId();
        }
    }
}

启动网站时,_userBLL为空。我的DI在某个地方失败了。

非常感谢。

1 个答案:

答案 0 :(得分:0)

您是否已注册httpHandler?来自Spring documentation

<system.web>
  <httpHandlers>
    <add verb="*" path="*.aspx" type="Spring.Web.Support.PageHandlerFactory, Spring.Web"/>
  </httpHandlers>
  <httpModules>
    <add name="Spring" type="Spring.Context.Support.WebSupportModule, Spring.Web"/>
  </httpModules>
  ...
</system.web>