Tôi đang cố gắng tìm ra cách chính xác cách liên kết thứ gì đó như thế này với số thập phân.Sự phụ thuộc theo chu kỳ với ninject
interface IMainService
{
void DoStuff();
}
interface IOtherService
{
void DoSomeMagic();
}
abstract class BaseClass
{
//many stuff here
}
class MainClass : BaseClass, IMainService
{
public MainClass(IOtherService s)
{
}
public void DoStuff()
{
throw new NotImplementedException();
}
//do many other things
}
class OtherClass : IOtherService
{
public OtherClass(IMainService s)
{
}
public void DoSomeMagic()
{
throw new NotImplementedException();
}
}
class BaseModule : NinjectModule
{
public override void Load()
{
Bind<MainClass>().To<MainClass>();
Bind<IMainService>().To<MainClass>();
Bind<IOtherService>().To<OtherClass>();
}
}
static class Program
{
static void Main()
{
var kernel = new StandardKernel(new BaseModule());
var main = kernel.Get<MainClass>();
}
}
Nó mang lại cho tôi ngoại lệ:
Error activating IOtherService using binding from IOtherService to OtherClass
A cyclical dependency was detected between the constructors of two services.
Activation path:
4) Injection of dependency IOtherService into parameter s of constructor of type MainClass
3) Injection of dependency IMainService into parameter s of constructor of type OtherClass
2) Injection of dependency IOtherService into parameter s of constructor of type MainClass
1) Request for MainClass
Suggestions:
1) Ensure that you have not declared a dependency for IOtherService on any implementations of the service.
2) Consider combining the services into a single one to remove the cycle.
3) Use property injection instead of constructor injection, and implement IInitializable if you need initialization logic to be run after property values have been injected.
Tôi không biết làm thế nào để viết BaseModule. Tôi chỉ cần một ví dụ của MainClass và một ví dụ của OtherClass (như singletons).
tôi đã cố gắng điều như thế:
Bind<MainClass>().To<MainClass>().InSingletonScope();
Bind<IMainService>().To<MainClass>().InRequestScope();
Bind<IOtherService>().To<OtherClass>().InSingletonScope();
Nhưng với cùng một lỗi.
Và cách viết ràng buộc để chỉ sử dụng một phiên bản cho giao diện MainClass và IMainService?
Cảm ơn câu trả lời.
Cám ơn t tip của mình. Tôi tìm thấy giải pháp hoàn hảo với tiêm tài sản. Nhưng nó không có IOtherService OtherService {set; } trên IMainServices, bởi vì khi tôi trang trí tài sản với [Tiêm], Ninject thêm cá thể chính xác vào nó một mình. –
Điều này không hoạt động. Với phiên bản mới nhất của Ninject, nó sẽ ném một 'StackOverflowException' nếu bạn sử dụng thuộc tính tiêm cho cả hai, và sẽ ném" phụ thuộc chu kỳ đã được phát hiện "nếu chỉ có một là sử dụng tiêm tài sản (và tiêm constructor khác). –
Ah, nhưng nó * không * hoạt động miễn là bạn đang sử dụng phạm vi khác với phạm vi tạm thời (mặc định). –