2010-07-22 26 views
5

Tôi đang cố gắng Liên kết hai lớp cụ thể với một giao diện. Tôi nên sử dụng lệnh nào trong Ninject để thực hiện điều đó? Những gì tôi đang cố gắng làm là gắn hai lớp cụ thể vào một cơ sở giao diện trên tên bộ điều khiển. Điều đó có thể không? Tôi cho rằng trong ninject bạn sử dụng. Khi để cung cấp cho các điều kiện nhưng không có hướng dẫn ra có nơi họ cho bạn thấy làm thế nào để sử dụng. Khi cho ninject.Ninject để liên kết trên các bộ điều khiển khác nhau

Trả lời

8

Dưới đây là một vài ví dụ. Kiểm tra dự án nguồn Ninject và tiểu dự án thử nghiệm của nó cho các mẫu sử dụng khác nhau, đó là tài liệu tốt nhất cho nó, đặc biệt là vì các tài liệu chưa được cập nhật cho v2.

// usage of WhenClassHas attribute 
Bind<IRepository>().To<XmlDefaultRepository>().WhenClassHas<PageAttribute>().WithConstructorArgument("contentType", ContentType.Page); 
// usage of WhenInjectedInto 
Bind<IRepository>().To<XmlDefaultRepository>().WhenInjectedInto(typeof(ServicesController)); 
Bind<IRepository>().To<XmlDefaultRepository>().WhenInjectedInto(typeof(PageController)).WithConstructorArgument("contentType", ContentType.Page); 
Bind<IRepository>().To<XmlDefaultRepository>().WhenInjectedInto(typeof(WidgetZoneController)).WithConstructorArgument("contentType", ContentType.WidgetZone); 
// you can also do this 
Bind<IRepository>().To<PageRepository>().WhenInjectedInto(typeof(PageController)).WithConstructorArgument("contentType", ContentType.Page); 
Bind<IRepository>().To<WidgetZoneRepository>().WhenInjectedInto(typeof(WidgetZoneController)).WithConstructorArgument("contentType", ContentType.WidgetZone); 
// or this if you don't need any parameters to your constructor 
Bind<IRepository>().To<PageRepository>().WhenInjectedInto(typeof(PageController)); 
Bind<IRepository>().To<WidgetZoneRepository>().WhenInjectedInto(typeof(WidgetZoneController)); 
// usage of ToMethod() 
Bind<HttpContextBase>().ToMethod(context => new HttpContextWrapper(HttpContext.Current)); 

HTH

+0

tôi thử WhenInjectedInto() lệnh nhưng vẫn không làm việc cho tôi. Nếu bộ điều khiển của bạn có các tham số, bạn có thực sự cần phải thêm WithConstructorArgument() không? – Ganator

+0

Không có bộ điều khiển chỉ có một hàm tạo trong IRepository, nhưng việc triển khai IRepository (trong trường hợp của tôi là XmlDefaultRepository) có hàm tạo trong tham số contentType của chuỗi kiểu, đó là ví dụ với WithConstructorArgument() dành cho. – mare

+0

Xin lưu ý - khi các phương thức ...() và Với ...() có thể được chuỗi, bạn có thể dừng tại WhenInjectedInto(). Và, yeah, WhenInjectedInto() làm việc cho tôi out-of-the-box, rất đơn giản, miễn là việc thực hiện mẫu Repository của bạn cũng đơn giản. Bạn có thể đăng các mã cho giao diện kho lưu trữ của bạn và thực hiện nó và cho chúng tôi xem. Ngoài ra, hãy đăng mã từ global.asax.cs nơi bạn thiết lập DI. – mare

Các vấn đề liên quan