书本不好,我无法弄清我要接管的C#MVC项目中什么导致Controller构造函数始终传递存储库参数。
public partial class AdminController : ApiController
{
IDataRepository _repo;
public AdminController(IDataRepository repo)
{
_repo = repo;
}
}
其他不是局部的类也以这种方式编写。 我看了这些继承自的类(或接口)。 有任何想法吗? 提前致谢。
答案 0 :(得分:2)
这称为依赖注入。
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());
}
}
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>();
}
答案 1 :(得分:1)
这是Dependency Injection,请在启动时查看类似
的内容IDataRepository
这告诉依赖项注入容器使用DataRepo
的实例实例化={INPUT1!A1:C1,INPUT2!B1:C1;
{QUERY({INPUT1!A2:D}, "select Col1,Col2,Col3,' ',Col4 where Col1 is not null label ' '''");
QUERY({INPUT2!A2:D}, "select Col1,' ',' ',Col2,Col3 where Col1 is not null label ' ''',' '''")}}
。
答案 2 :(得分:1)
.net框架和.net核心对它的处理方式不同。
.net框架中根本没有内置它。您将需要检查global.asax文件,以了解发生了什么情况。大多数时候,它是通过nuget包完成的。有很多受欢迎的工具,例如autofaq,ninject,simplejector等。您应该看到一些有关构建容器和注册服务的信息。
.net核心具有其自己的依赖项注入框架,因此经常使用它。尽管有时人们仍然使用nuget包处理更复杂的事情。 .net核心内容将在Startup.cs文件中。看看是否有类似services.AddTransient的地方。
这是可能的,尽管不太可能有人在您的项目中编写自己的依赖项注入框架。在这种情况下,您会希望他们编写了ControllerFactory实现。
如果无法从此处弄清楚,请在您的问题中添加global.asax文件或startup.cs文件。