我如何使用注释来注入,这类似于Spring MVC的功能
public class AccountController :Controller
{
[Injected] // Need like this annotation
private AccountService _accountService;
public AccountController(){
}
}
答案 0 :(得分:1)
您可以使用Unity Container
以下是一个例子:
public class MyObject
{
private SomeOtherObject _dependentObject;
[Dependency]
public SomeOtherObject DependentObject
{
get { return _dependentObject; }
set { _dependentObject = value; }
}
}
这是决议:
IUnityContainer uContainer = new UnityContainer();
MyObject myInstance = uContainer.Resolve<MyObject>();
// now access the property containing the dependency
SomeOtherObject depObj = myInstance.DependentObject;
答案 1 :(得分:1)
在.Net核心应用程序中,无需提及注入注释。您需要将您的服务更改为接口驱动。
在解决方案启动页面中,在services.AddMvc();
之前添加以下显示的代码 services.AddTransient<IInterface, Service>();
并在控制器中进行更改
public class AccountController :Controller
{
private IAccountService _accountService;
public AccountController(IAccountService accountService){
_accountService = accountService;
}
}