如何在asp.net Web窗体上实现Ninject或DI?

如何在asp.net Web窗体上实现Ninject或DI?,asp.net,webforms,ninject,Asp.net,Webforms,Ninject,在MVC应用程序上使用它有很多例子。它是如何在Web表单上完成的?请查看Steve Sanderson(Apress)的《Pro ASP.NET MVC 2框架,第二版》一书。作者使用Ninject连接数据库。我认为您可以使用这些示例,并根据自己的需要进行调整。看看Ninject.Web扩展。它提供了基本的基础设施 我认为以下是在ASP.NET Web窗体上实现Ninject.Web的步骤 在Global.asax上实现NinjectHttpApplication。对于内核,通过实现Ninjec

在MVC应用程序上使用它有很多例子。它是如何在Web表单上完成的?

请查看Steve Sanderson(Apress)的《Pro ASP.NET MVC 2框架,第二版》一书。作者使用Ninject连接数据库。我认为您可以使用这些示例,并根据自己的需要进行调整。

看看Ninject.Web扩展。它提供了基本的基础设施
我认为以下是在ASP.NET Web窗体上实现Ninject.Web的步骤

  • 在Global.asax上实现NinjectHttpApplication。对于内核,通过实现NinjectModule将其传入
  • 在代码隐藏处的每个web表单页面加载事件上,实现Ninject.web.PageBase。添加实例类,并在其顶部添加[Inject]过滤器
  • 关于更详细的示例,以下是我发现的一些有用的链接:

    一,


    2.

    以下是将Ninject与WebForms结合使用的步骤

    步骤1-下载

    需要两次下载-和WebForm扩展(有NLog替代方案)

    需要在web应用程序中引用以下文件:Ninject.dll、Ninject.web.dll、Ninject.Extensions.Logging.dll和Ninject.Extensions.Logging.Log4net.dll

    第2步-全局.asax

    全局类需要从
    Ninject.Web.NinjectHttpApplication
    派生,并实现
    CreateKernel()
    ,从而创建容器:

    using Ninject; using Ninject.Web;
    
    namespace Company.Web {
        public class Global : NinjectHttpApplication
    
    
            protected override IKernel CreateKernel()
            {
                IKernel kernel = new StandardKernel(new YourWebModule());
                return kernel;
            }
    
    StandardKernel
    构造函数接受一个
    模块

    步骤3-模块

    在本例中,模块定义了web应用程序需要的所有绑定:

    using Ninject;
    using Ninject.Web;
    
    namespace Company.Web
    {
        public class YourWebModule : Ninject.Modules.NinjectModule
        {
    
            public override void Load()
            {
                Bind<ICustomerRepository>().To<CustomerRepository>();
            }   
    
    InjectAttribute-[Inject]
    -告诉Ninject将
    ICCustomerRepository
    注入CustomerRepo属性

    如果您已经有了一个基本页面,那么您只需要从Ninject.Web.PageBase获取基本页面即可

    第5步-母版页

    不可避免地,您将拥有母版页,为了允许母版页访问注入的对象,您需要从
    Ninject.Web.MasterPageBase
    派生母版页:

      using Ninject;
        using Ninject.Web;
        namespace Company.Web
        {
            public partial class Default : PageBase
            {
                [Inject]
                public ICustomerRepository CustomerRepo { get; set; }
    
                protected void Page_Load(object sender, EventArgs e)
                {
                    Customer customer = CustomerRepo.GetCustomerFor(int customerID);
                }
    
    using Ninject;
    using Ninject.Web;
    
    namespace Company.Web
    {
        public partial class Site : MasterPageBase
        {
    
            #region Properties
    
            [Inject]
            public IInventoryRepository InventoryRepo { get; set; }     
    
    using Ninject;
    using Ninject.Web;    
    namespace Company.Web.Services
    {
    
        [WebService(Namespace = "//tempuri.org/">http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]    
        [System.Web.Script.Services.ScriptService]
        public class YourWebService : WebServiceBase
        {
    
            #region Properties
    
            [Inject]
            public ICountbackRepository CountbackRepo { get; set; }
    
            #endregion
    
            [WebMethod]
            public Productivity GetProductivity(int userID)
            {
                CountbackService _countbackService =
                    new CountbackService(CountbackRepo, ListRepo, LoggerRepo);
    
    步骤6-静态Web服务方法

    下一个问题是无法注入静态方法。我们有一些Ajax页面方法,它们显然是静态的,所以我不得不将这些方法转移到一个标准的web服务中。同样,web服务需要从Ninject类派生-
    Ninject.web.WebServiceBase

      using Ninject;
        using Ninject.Web;
        namespace Company.Web
        {
            public partial class Default : PageBase
            {
                [Inject]
                public ICustomerRepository CustomerRepo { get; set; }
    
                protected void Page_Load(object sender, EventArgs e)
                {
                    Customer customer = CustomerRepo.GetCustomerFor(int customerID);
                }
    
    using Ninject;
    using Ninject.Web;
    
    namespace Company.Web
    {
        public partial class Site : MasterPageBase
        {
    
            #region Properties
    
            [Inject]
            public IInventoryRepository InventoryRepo { get; set; }     
    
    using Ninject;
    using Ninject.Web;    
    namespace Company.Web.Services
    {
    
        [WebService(Namespace = "//tempuri.org/">http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]    
        [System.Web.Script.Services.ScriptService]
        public class YourWebService : WebServiceBase
        {
    
            #region Properties
    
            [Inject]
            public ICountbackRepository CountbackRepo { get; set; }
    
            #endregion
    
            [WebMethod]
            public Productivity GetProductivity(int userID)
            {
                CountbackService _countbackService =
                    new CountbackService(CountbackRepo, ListRepo, LoggerRepo);
    
    在JavaScript中,您需要引用标准服务--
    Company.Web.Services.YourWebService.GetProductivity(user,onSuccess)
    ,而不是
    PageMethods.GetProductivity(user,onSuccess)

    我发现的另一个问题是将对象注入到用户控件中。虽然可以使用Ninject功能创建自己的基本UserControl,但我发现在用户控件中添加所需对象的属性并在容器页面中设置属性会更快。我认为支持开箱即用的用户控件在Ninject“待办事项”列表中


    添加Ninject非常简单,它是一个雄辩的IoC解决方案。许多人喜欢它,因为没有Xml配置。它还有其他有用的“窍门”,比如用Ninject语法将对象转换为单例-
    Bind().To().InSingletonScope()
    。没有必要将WebLogger更改为实际的单例实现,我喜欢这样。

    随着Ninject v3.0的发布(截至2012年4月12日),它变得更容易了。注入是通过HttpModule实现的,因此不需要让页面从自定义页面/母版页继承。以下是快速扣球的步骤(和代码)

  • 创建新的ASP.NET WebForms项目
  • 使用NuGet添加Ninject.Web库(这也将关闭Ninject.Web.Common和Ninject库)
  • 在App_Start/NinjectWebCommon.cs/RegisterServices方法中注册自定义绑定
  • 在页面上使用属性注入
  • NinjectWebCommon/RegisterServices

    地点,主人

    模型

    输出窗口的结果

    由于故障,当前无法工作。这里是@Jason步骤的一个修改版本,它使用客户httpmodule注入页面和控件,而无需从ninject类继承

  • 创建新的ASP.NET WebForms项目
  • 使用NuGet添加Ninject.Web库
  • 在App_Start/NinjectWebCommon.cs/RegisterServices方法中注册自定义绑定
  • 添加InjectPageModule并在NinjectWebCommon中注册
  • 在页面上使用属性注入
  • 输入pagemodule.cs

    地点,主人

    模型

    输出窗口的结果

    _上下文对象以某种方式被设置为null。以下是其余的设置

    public partial class CreateGoal : Page
    {
        [Inject]
        public IGoalsService_CRUD _context { get; set; }
    }
    
    用于全局文件

    protected override IKernel CreateKernel()
    {
        IKernel kernel = new StandardKernel(new Bindings());
        return kernel;
    }
    
    public class Bindings : NinjectModule
    {
        public override void Load()
        {
            Bind<goalsetterEntities>().To<goalsetterEntities>();
            Bind<IGoalsService_CRUD>().To<GoalsService_CRUD>();
        }
    }
    
    protectedoverride IKernel CreateKernel()
    {
    IKernel kernel=新的标准内核(新绑定());
    返回内核;
    }
    公共类绑定:NinjectModule
    {
    公共覆盖无效负载()
    {
    绑定()到();
    绑定()到();
    }
    }
    
    是的,我有一个问题促使我问这个问题。如果web应用程序是web表单,它是如何实现的?这也是我在web表单中通常使用的方式。诀窍是你需要使用内核的Get方法。这假设你已经添加了Ninject.Web扩展,这正是你需要做的。@nelly,这两个链接现在都失效了。joeandcode.net链接现在失效了。存档版本在这里:我知道我应该以身作则,但自述文件应该>0字节@鲁本:我同意更新docu是atm名单上最重要的任务之一。这都是关于优先级和来自社区的帮助。在过去的一年中添加了大量文档。不是因为NITCUP.WEB,因为我认为它比其他特性更重要,因为:a)WebFras是过时的——使用MVC而不是B)i
     public class InjectPageModule : DisposableObject, IHttpModule
    {
        public InjectPageModule(Func<IKernel> lazyKernel)
        {
            this.lazyKernel = lazyKernel;
        }
    
        public void Init(HttpApplication context)
        {
            this.lazyKernel().Inject(context);
            context.PreRequestHandlerExecute += OnPreRequestHandlerExecute;
        }
    
        private void OnPreRequestHandlerExecute(object sender, EventArgs e)
        {
            var currentPage = HttpContext.Current.Handler as Page;
            if (currentPage != null)
            {
                currentPage.InitComplete += OnPageInitComplete;
            }
        }
    
        private void OnPageInitComplete(object sender, EventArgs e)
        {
            var currentPage = (Page)sender;
            this.lazyKernel().Inject(currentPage);
            this.lazyKernel().Inject(currentPage.Master);
            foreach (Control c in GetControlTree(currentPage))
            {
                this.lazyKernel().Inject(c);
            }
    
        }
    
        private IEnumerable<Control> GetControlTree(Control root)
        {
            foreach (Control child in root.Controls)
            {
                yield return child;
                foreach (Control c in GetControlTree(child))
                {
                    yield return c;
                }
            }
        }
    
        private readonly Func<IKernel> lazyKernel;
    }
    
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<IHttpModule>().To<InjectPageModule>();
            kernel.Bind<IAmAModel>().To<Model1>();
    
        } 
    
    public partial class _Default : System.Web.UI.Page
    {
    
        [Inject]
        public IAmAModel Model { get; set; }
    
        protected void Page_Load(object sender, EventArgs e)
        {
            System.Diagnostics.Trace.WriteLine(Model.ExecuteOperation());
        }
    }
    
    public partial class SiteMaster : System.Web.UI.MasterPage
    {
    
        [Inject]
        public IAmAModel Model { get; set; }
    
        protected void Page_Load(object sender, EventArgs e)
        {
            System.Diagnostics.Trace.WriteLine("From master: " 
                + Model.ExecuteOperation());
        }
    }
    
    public interface IAmAModel
    {
        string ExecuteOperation();         
    }
    
    public class Model1 : IAmAModel
    {
        public string ExecuteOperation()
        {
            return "I am a model 1";
        }
    }
    
    public class Model2 : IAmAModel
    {
        public string ExecuteOperation()
        {
            return "I am a model 2";
        }
    }
    
    I am a model 1
    From master: I am a model 1
    
    public IGoalsService_CRUD _context { get; set; }
    
    public partial class CreateGoal : Page
    {
        [Inject]
        public IGoalsService_CRUD _context { get; set; }
    }
    
    protected override IKernel CreateKernel()
    {
        IKernel kernel = new StandardKernel(new Bindings());
        return kernel;
    }
    
    public class Bindings : NinjectModule
    {
        public override void Load()
        {
            Bind<goalsetterEntities>().To<goalsetterEntities>();
            Bind<IGoalsService_CRUD>().To<GoalsService_CRUD>();
        }
    }