C# 使用ninject将存储库注入winform错误
我正在使用Ninject将我的存储库注入我的windows窗体 因此,我从nuget安装ninject。我将其添加到我的窗口窗体:C# 使用ninject将存储库注入winform错误,c#,winforms,repository,ninject,C#,Winforms,Repository,Ninject,我正在使用Ninject将我的存储库注入我的windows窗体 因此,我从nuget安装ninject。我将其添加到我的窗口窗体: public class Binding: NinjectModule { public override void Load() { Bind<IUserRepository>().To<IUserRepository>(); } } 另外,在这种情
public class Binding: NinjectModule
{
public override void Load()
{
Bind<IUserRepository>().To<IUserRepository>();
}
}
另外,在这种情况下,
[Inject]
属性是没有意义的,因为您没有注入任何东西-您自己直接从容器创建依赖项(这是可以的,尽管您可以进行适当的注入,请参阅以获取一些想法,这也适用于Ninject)谢谢Stephen,这是我的问题好东西;我还用一个值得一读的链接更新了答案,因为它将向您展示如何进行适当的注入,从而可以在表单的构造函数中声明IUserRepository,这要简洁得多:)
public partial class Form1 : Form
{
private IUserRepository userRepository;
[Inject]
public Form1()
{
InitializeComponent();
var kernel = new StandardKernel();
kernel.Load(Assembly.GetExecutingAssembly());
userRepository = kernel.Get<IUserRepository>();
}
private void Form1_Load(object sender, EventArgs e)
{
List<User> saaa = userRepository.Get().ToList();
int aaa = saaa.Count;
}
}
An unhandled exception of type 'Ninject.ActivationException' occurred in Ninject.dll
Additional information: Error activating IUserRepository using binding from IUserRepository to IUserRepository
No constructor was available to create an instance of the implementation type.
Activation path:
1) Request for IUserRepository
Suggestions:
1) Ensure that the implementation type has a public constructor.
2) If you have implemented the Singleton pattern, use a binding with InSingletonScope() instead.
Bind<IUserRepository>().To<IUserRepository>();
Bind<IUserRepository>().To<UserRepository>();