关于使用 autoFac 的注入方法
2024-08-30 22:30:15
1、使用 NUGET 安装 Autofac
2、需要引用Autofac ASP.NET MVC 5 Integration 这个扩展包。
但有时候在NuGet中找不到 该包 需要使用“程序要控制器控制台”安装
输入 安装解决
Install-Package Autofac.Mvc5 -Version 4.0.2
安装完成后引用里面就多了Autofac.dll和Autofac.Intergration.MVC,如果是在webApi里使用Autofac需要安装Autofac ASP.NET Web API2.2 Intergration 才可以。
install-package autofac.webapi2
3、使用方法,以下方式引用 https://www.cnblogs.com/zjoch/p/6485170.html 博客
新建一个person实体类
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
新建一个person仓储接口
public interface IPersonRepository
{
IEnumerable<Person> GetAll();
Person Get(int id);
Person Add(Person item);
bool Update(Person item);
bool Delete(int id);
}
新建一个person仓储
public class PersonRepository : IPersonRepository
{
List<Person> person = new List<Person>(); public PersonRepository()
{
Add(new Person { Id = 1, Name = "joye.net1", Age = 18, Address = "中国上海" });
Add(new Person { Id = 2, Name = "joye.net2", Age = 18, Address = "中国上海" });
Add(new Person { Id = 3, Name = "joye.net3", Age = 18, Address = "中国上海" });
}
public IEnumerable<Person> GetAll()
{
return person;
}
public Person Get(int id)
{
return person.Find(p => p.Id == id);
}
public Person Add(Person item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
person.Add(item);
return item;
}
public bool Update(Person item)
{
if (item == null)
{
throw new ArgumentNullException("item");
} int index = person.FindIndex(p => p.Id == item.Id);
if (index == -1)
{
return false;
}
person.RemoveAt(index);
person.Add(item);
return true;
}
public bool Delete(int id)
{
person.RemoveAll(p => p.Id == id);
return true;
}
}
Global属性注入
public class MvcApplication : System.Web.HttpApplication
{
private void SetupResolveRules(ContainerBuilder builder)
{
builder.RegisterType<PersonRepository>().As<IPersonRepository>();
}
protected void Application_Start()
{
var builder = new ContainerBuilder();
SetupResolveRules(builder);
builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
效果图
最新文章
- Linux 中优秀的文本化编辑思想大碰撞(Markdown、LaTeX、MathJax)
- jsrender for array 和for object语法
- Java NIO之选择器Selector
- java8 引进lamda
- Charles的使用
- Qt 与 JavaScript 通信
- AVAudioPlayer的锁屏播放控制和锁屏播放信息显示
- PHP入门小练习
- database锁实现
- vue-cli2 构建速度优化
- CentOS7使用firewalld打开关闭防火墙与端口[转]
- JavaScript 正则表达式 通俗解释 快速记忆
- Python 技术点
- Dance GAN 迁移不同视频中人物动作的方法
- linux使用mail命令发送邮件
- linux 常用awk命令
- Unity3d之Perfab
- String调用Array相关方法——有点古怪
- Address already in use: JVM_Bind,tomcat启动异常
- 转python调用Go代码