c# - .NET MVC + Unity:需要一些基本帮助
问题描述
使用 Identity 和 EF 的 MVC 应用程序。
我想使用 Unity 实现依赖注入。我已经在项目中安装了 Unity(Unity 和 Unity.mvc5),但现在我迷失了如何实现它......截至目前,(在更改任何内容之前)我在每个控制器中实例化 dbcontext,然后在控制器构造函数中我使用 new xxxx(db) 创建服务实例。
我的控制器是这样的:
public class SomeController : Controller {
private ApplicationDbContext db = new ApplicationDbContext("DefaultConnection");
private XxService xxService;
public SomeController() {
this.xxService = new XxService(db);
}
public ActionResult Index() {
string name = xxService.Foo(5);
return View();
}
}
然后我有我的服务:
public class XxService {
private ApplicationDbContext db;
private YyService yyService;
public XxService(ApplicationDbContext db) {
this.db = db;
this.yyService = new YyService(db);
}
public string Foo(int id) {
Customer customer = yyService.Bar(id);
return customer.Name;
}
}
public class YyService {
private ApplicationDbContext db;
public YyService(ApplicationDbContext db) {
this.db = db;
}
public Customer Bar(int id) {
return db.Customers.Find(id);
}
}
和统一配置:
public static class UnityConfig {
public static void RegisterComponents() {
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
//container.RegisterType<XxService>(new Unity.Injection.InjectionConstructor());
}
}
我真的不明白我应该在 Unity 配置中注册什么以及如何注册,和/或我应该创建哪些界面......我应该注册服务吗?数据库上下文?两个都?如何?一些代码会很棒,这让我发疯......
解决方案
推荐阅读
- delphi - 如何在运行时将项目添加到 TStackPanel
- java - 在 requestCode 中使用什么
- javascript - jQuery循环切片
- c# - 通过 API 使用 .NET Core 标识
- security - 大型公司如何实施隐私和用户访问控制
- javascript - 带有 ajax 表的 Django 模态表单
- docker - 在从 docker 文件构建的容器内的 python 文件中使用 Dockerfile 中的 ARG 变量
- image - 数码相机拍摄的照片中存储了哪些额外信息?
- amazon-elastic-beanstalk - 我可以使用脚本创建 ebextension 配置文件吗?
- arrays - Matlab:用最后一个非零索引替换零