public class Author
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public interface IAuthorRepository
{
bool Create(Author author);
Author Read(int id);
List<Author> Read();
}
public class AuthorRepository : IAuthorRepository
{
public bool Create(Author author)
{
throw new System.NotImplementedException();
}
public Author Read(int id)
{
throw new System.NotImplementedException();
}
public List<Author> Read()
{
throw new System.NotImplementedException();
}
}
using Microsoft.AspNet.WebFormsDependencyInjection.Unity;
using System;
using System.Web;
using System.Web.Optimization;
using System.Web.Routing;
using Unity;
namespace WebformsDIDemo
{
public class Global : HttpApplication
{
void Application_Start(object sender, EventArgs e)
{
var container = this.AddUnity();
container.RegisterType<IAuthorRepository, AuthorRepository>();
// Code that runs on application startup
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
public partial class _Default : Page
{
private IAuthorRepository _authorRepository;
public _Default(IAuthorRepository authorRepository)
{
_authorRepository = authorRepository;
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
上面的图很明显的显示了,authorRepository 实例在运行时中已被成功注入 。
在 .Net Framework 4.7.2 框架以上,终于将 依赖注入机制 带入到了 ASP.Net Web Forms 中,需要明白的是,微软自带的Unity包是一个轻量级的依赖注入容器,可以在 页面,控件,handler,module 上使用,在 ASP.Net Web Forms 中使用依赖注入可以轻松创建对象,然后在运行时获取依赖,可让你轻松构建灵活,松散的应用程序 。
以上就是在ASP.Net Web Forms中使用依赖注入的步骤的详细内容,更多关于ASP.Net Web Forms中使用依赖注入的资料请关注脚本之家其它相关文章!