简体   繁体   English

在MVC中使用ServiceStack Funq依赖注入

[英]Using ServiceStack Funq Dependency Injection in MVC

In ServicePlugin.cs, I have defined this in the Register() method: 在ServicePlugin.cs中,我在Register()方法中定义了此方法:

container.RegisterAutoWiredAs<ApplicationUserProfileRepository, 
    IApplicationUserRepository>().ReusedWithin(ReuseScope.Request);

I then, have a ServiceStack service which attempts to resolve it as a normal dependency: 然后,我有了一个ServiceStack服务,尝试将其解析为正常的依赖项:

public class UserService : ServiceStack.Service
{

    private readonly IApplicationUserRepository _repository;

    public UserService(IApplicationUserRepository rep)
    {
        _repository = rep;
    }

Finally, in my MVC controller, I am attempting to call the service like so: 最后,在我的MVC控制器中,我试图像这样调用服务:

using (UserService action = new UserService(new ApplicationUserProfileRepository()))
{
    // etc...

The code above works fine; 上面的代码工作正常; but instead, I want to have the dependency injected automatically so that I can simply do this: 但是,我想让依赖项自动注入,以便我可以简单地做到这一点:

using (UserService action = new UserService())
{
    // etc...

Is this not how dependency injection is supposed to be done with Service Stack and MVC? 这不是应该使用Service Stack和MVC进行依赖注入的方式吗?

Note: I got the example from here https://github.com/ServiceStack/ServiceStack/wiki/The-IoC-container 注意:我从这里获得了示例https://github.com/ServiceStack/ServiceStack/wiki/The-IoC-container

Simplifying injection: 简化注射:

If you make the repository a public property on the UserService then Funq will inject the dependancy automatically when you resolve the Service, given that you have registered it with the container, so you don't have to add it via the constructor. 如果将存储库设为UserService上的public属性,则在解析Service时,Funq将自动注入依赖项,因为您已经在容器中注册了依赖项,因此不必通过构造函数添加依赖项。 Though your method of constructor injection will still work, given you follow the resolve instructions below. 尽管您的构造函数注入方法仍然可以使用,但是请遵循以下解析说明。

Make the repository public : public存储库:

public class UserService : ServiceStack.Service
{
    public IApplicationUserRepository Repository { get; set; }
}

Register the repository instance with the container: 向容器注册存储库实例:

HostContext.Container.Register<IApplicationUserRepository>(c => new ApplicationUserProfileRepository()).ReusedWithin(ReuseScope.Request);

Get instance by resolving from the Funq Container: 通过从Funq容器解析来获取实例:

Then when you want to use the UserService resolve it rather than creating the instance directly, it's this action which will ensure the dependancies are injected: 然后,当您要使用UserService解析它而不是直接创建实例时,此操作将确保注入依赖项:

using(var userService = HostContext.ResolveService<UserService>())
{
    // Dependancy is already wired up
    userService.Repository ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM