简体   繁体   English

如何在 asp.net core 中注入特定的实现

[英]How to inject a specific implementation in asp.net core

I have a Repository which has a dependency of User我有一个依赖于User的存储库

I need to put other implementation of User and I can do it like that, but with this approach I do not know how to mock my repository我需要放置User的其他实现,我可以这样做,但是使用这种方法我不知道如何模拟我的存储库

private readonly IRepository<Entity> _repository;

public SomeClass(MyAppDbContext context)
{
  _repository= new EfRepository<WorkOrder>(context, new User());
}

Is there a way to inject a specific implementation of User here, or how I can test the code I wrote有没有办法在这里注入User的特定实现,或者我如何测试我写的代码

Just as you inject MyAppDbContext into SomeClass you can also inject an instance of User , eg就像您将MyAppDbContext注入SomeClass一样,您也可以注入User的实例,例如

private readonly IRepository<Entity> _repository;

public SomeClass(MyAppDbContext context, User user)
{
  _repository= new EfRepository<WorkOrder>(context, user);
}

You can either register User in the IoC like this:您可以像这样在 IoC 中注册User

services.AddTransient<User>();

In case you have already registered a service for User and want to use another instance, you can register a factory method for SomeClass that sets up the User instance:如果您已经为User注册了一个服务并且想要使用另一个实例,您可以为SomeClass注册一个工厂方法来设置User实例:

services.AddScoped<SomeClass>(prov => new SomeClass(
  prov.GetRequiredService<MyAppDbContext>(), 
  new User()));

The factory method approach is viable if you only have a few spots that need the special instance, otherwise you can use this approach: Unlike other IoCCs, the .NET Core IoCC does not support named registrations, but you can also use some kind of "marker interface" to register another instance:如果您只有几个需要特殊实例的地方,工厂方法方法是可行的,否则您可以使用这种方法:与其他 IoCC 不同,.NET Core IoCC 不支持命名注册,但您也可以使用某种“标记接口”来注册另一个实例:

public interface ISpecialUser : IUser {}

public class User : IUser
{
  // ...
}

public class AnotherUser : ISpecialUser
{
  // ...
}

// ...
public SomeClass(MyAppDbContext context, ISpecialUser user)
{
  _repository= new EfRepository<WorkOrder>(context, user);
}


// ...
services.AddScoped<IUser, User>();
services.AddScoped<ISpecialUser, AnotherUser>();

In the tests, you can set up an instance of User that suits your needs and use the new constructor parameter.在测试中,您可以设置适合您需要的User实例并使用新的构造函数参数。

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

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