2011-12-24 52 views
7

Tôi có các lớp như AccountsController, ProductsController vv mà tất cả được kế thừa từ BaseController. Unity thiết lập các dịch vụ của tôi khi cần thiết. Các lớp này cũng yêu cầu dịch vụ _sequence. Vì nó là một yêu cầu chung cho tất cả các lớp tôi muốn mã này trong BaseController.Gọi hàm tạo siêu trong C#

public class AccountsController : BaseController 
{ 
    public AccountsController(
     IService<Account> accountService) { 
     _account = accountService; 
    } 

public class ProductsController : BaseController 
{ 
    public ProductsController(
     IService<Account> productService) { 
     _product = productService; 
    } 


public class BaseController : Controller 
{ 
    public IService<Account> _account; 
    public IService<Product> _product; 
    protected ISequenceService _sequence; 

    public BaseController(
     ISequenceService sequenceService) { 
     _sequence = sequenceService; 
    } 

Nhưng làm cách nào tôi có thể thực hiện việc này? Tôi có nên thiết lập một cuộc gọi đến BaseController bên trong các nhà xây dựng của mỗi AccountController và ProductsController không?

Trả lời

12

Bạn có thể chuỗi constructors:

public class ProductsController : BaseController 
{ 
    public ProductsController(
     IService<Account> productService) : base(productService) 
    { 
     _product = productService; 
    } 
} 

Lưu ý rằng xích BaseController (sử dụng từ khóa base) đã được thông qua tham số productService, khó khăn này có thể là bất cứ điều gì.

Cập nhật:

Bạn có thể làm (dependency injection mans nghèo) sau:

public class ProductsController : BaseController 
{ 
    public ProductsController(
     IService<Account> productService) : base(new SequenceService()) 
    { 
     _product = productService; 
    } 
} 

Hoặc, vượt qua trong sự phụ thuộc vào ISequenceService thông qua các loại kế thừa của bạn:

public class ProductsController : BaseController 
{ 
    public ProductsController(
     IService<Account> productService, ISequenceService sequenceService) 
     : base(sequenceService) 
    { 
     _product = productService; 
    } 
} 
+0

Tôi xin lỗi. Tôi không hiểu ví dụ của bạn. Những gì tôi cần là xây dựng BaseConstructor và sequenceService. –

+0

@ Samantha2 - Trả lời được cập nhật với các tùy chọn. – Oded

+0

Đã xem nhận xét của bạn về DI nhưng tôi đã sử dụng Unity để tiêm phụ thuộc. Tôi không thể làm điều này với Unity? Tôi tự hỏi làm thế nào Unity hoạt động vì nó đã thiết lập AccountController của tôi và các cá thể cấp dữ liệu vào nó. Điều gì sẽ xảy ra nếu tôi thực hiện cuộc gọi đến BaseController. Unity sẽ không bắt được điều này và thiết lập SequenceService tự động? –

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