kirov-opensource / NAutowired

ASP.NET CORE Field Injection Implement
MIT License
77 stars 16 forks source link

对泛型注入有支持吗?比如某些场景Repository<TEntity> #5

Closed chenbigit closed 4 years ago

chenbigit commented 4 years ago

目前提示NAutowired.Core.Exceptions.UnableResolveDependencyException: Unable to resolve dependency

FatTigerWang commented 4 years ago

有代码片段或者样例吗

FatTigerWang commented 4 years ago

是否以下这种情况:

public interface IRepository
{
    string GetEntityName();
}

[NAutowired.Core.Attributes.Repository]
public class Repository<TEntity> : IRepository
{
    public string GetEntityName()
    {
        return typeof(TEntity).Name;
    }
}

//在控制器中想要还原出Repository<User>
public class UserController : ControllerBase
{
    [Autowired(typeof(Repository<User>))]
    private readonly IRepository userRepository;

    [HttpGet]
    public string Get()
    {
        return userRepository.GetEntityName();
    }
}

如果是上面这种情况,你有两种解决方案:

先决条件:NAutowired >= 2.0.1

// in UserController [Autowired(typeof(Repository))] private readonly IRepository userRepository;

[HttpGet] public string Get() { return userRepository == null ? "failure" : "success"; }

* 另一种方案是您可以使用`UserRepository<User>`继承自`Repository<TEntity>`,并且用`[Repository(implementInterface: typeof(IRepository))]`的方式继续使用自动添加到容器的方法。
```csharp
// in UserRepository
[Repository(implementInterface: typeof(IRepository))]
public class UserRepository: Repository<User> 
{
}

// in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers().AddControllersAsServices();
    //replace `IControllerActivator` implement.
    services.Replace(ServiceDescriptor.Transient<IControllerActivator, NAutowiredControllerActivator>());
    //use auto dependency injection
    services.AutoRegisterDependency(assemblies);
}

// in UserController
[Autowired(typeof(UserRepository))]
private readonly IRepository userRepository;

[HttpGet]
public string Get()
{
    return userRepository == null ? "failure" : "success";
}
chenbigit commented 4 years ago

明白了,谢谢