首页 > 解决方案 > .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 配置中注册什么以及如何注册,和/或我应该创建哪些界面......我应该注册服务吗?数据库上下文?两个都?如何?一些代码会很棒,这让我发疯......

标签: c#asp.net-mvcunity3d

解决方案



推荐阅读