Closed chenbigit closed 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();
}
}
如果是上面这种情况,你有两种解决方案:
Startup.cs
中,使用services.AddScoped(typeof(IRepository), typeof(Repository<User>))
的方式注入到容器,然后在Controller
使用[Autowired(typeof(Repository<User>))]
还原,这意味着你没法使用程序集自动注入的方法,因为你的Repository<TEntity>
是泛型,需要你一个个在Startup.cs
注入到容器。
// in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddControllersAsServices();
//replace `IControllerActivator` implement.
services.Replace(ServiceDescriptor.Transient<IControllerActivator, NAutowiredControllerActivator>());
services.AddTransient<IRepository, Repository<User>>();
//services.AddTransient<IRepository, Repository<OtherEntity>>();
}
// in UserController
[Autowired(typeof(Repository
[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";
}
明白了,谢谢
目前提示NAutowired.Core.Exceptions.UnableResolveDependencyException: Unable to resolve dependency