繁体   English   中英

如何设置控制器,以便使用存储库参数调用构造函数

[英]How to set up controller so constructor gets called with repository argument

书本不好,我无法弄清楚我要接管的C#MVC项目中的什么导致Controller构造函数始终传递给存储库参数。

  public partial class AdminController : ApiController
  {
    IDataRepository _repo;
    public AdminController(IDataRepository repo)
    {
      _repo = repo;
    }
  }

甚至其他非局部类也以这种方式编写。 我看了这些继承自的类(或接口)。 有任何想法吗? 提前致谢。

这称为依赖注入。

Asp.net核心具有内置的DI容器。 但是对于旧的Asp.net项目,您应该添加一个库以使用它。 我不知道您使用哪个库,但是我可以举一些常见的例子:

简单喷油器

https://simpleinjector.readthedocs.io/en/latest/aspnetintegration.html

// You'll need to include the following namespaces
using System.Web.Mvc;
using SimpleInjector;
using SimpleInjector.Integration.Web;
using SimpleInjector.Integration.Web.Mvc;

// This is the Application_Start event from the Global.asax file.
protected void Application_Start(object sender, EventArgs e) {
    // Create the container as usual.
    var container = new Container();
    container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();

    // Register your types, for instance:
    container.Register<IUserRepository, SqlUserRepository>(Lifestyle.Scoped);

    // This is an extension method from the integration package.
    container.RegisterMvcControllers(Assembly.GetExecutingAssembly());

    container.Verify();

    DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
}

温莎城堡

https://gist.github.com/martinnormark/3128275

    public class ControllersInstaller : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(AllTypes.FromThisAssembly()
                .Pick().If(t => t.Name.EndsWith("Controller"))
                .Configure(configurer => configurer.Named(configurer.Implementation.Name))
                .LifestylePerWebRequest());
        }
    } 

Asp.net核心

https://docs.microsoft.com/tr-tr/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.2

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddScoped<IMyDependency, MyDependency>();
}

这是Dependency Injection ,可以在启动时查看类似

services.AddTransiant<IDataRepository, DataRepo>();

这告诉依赖项注入容器使用DataRepo的实例实例化IDataRepository

就像其他人所说的,依赖注入。 但还有更多细节:

.net框架和.net核心以不同的方式处理它。

它根本没有内置在.net框架中。 您将需要检查global.asax文件,以了解发生了什么情况。 大多数时候,它是通过nuget包完成的。 有很多受欢迎的工具,例如autofaq,ninject,简单的注射器等。您应该看到一些有关构建容器和注册服务的知识。

.net核心具有其自己的依赖项注入框架,因此经常使用它。 尽管有时人们仍然使用nuget包处理更复杂的事情。 .net核心内容将在Startup.cs文件中。 看看是否有类似services.AddTransient的地方。

有可能,尽管不太可能有人在您的项目中编写自己的依赖注入框架。 在这种情况下,您将寻找他们编写了ControllerFactory实现。

如果您不能从这里弄清楚,请在您的问题中添加global.asax文件或startup.cs文件。

暂无
暂无

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

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