构造函数不起作用的依赖注入

时间:2013-10-20 19:31:58

标签: ninject

我有以下代码

SmtpSection smtpsection = 
       (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");

EmailSettings emailSettings = new EmailSettings
        {
            WriteAsFile = bool.Parse(ConfigurationManager.AppSettings[""] ?? "false"),
            ServerPort = smtpsection.Network.Port,
            Username = smtpsection.Network.UserName,
            Password = smtpsection.Network.Password,
            UseSsl = smtpsection.Network.EnableSsl
        };

kernel.Bind<IEmailRepository>().To<EmailRepository>().WithConstructorArgument("settings", emailSettings);

public class EmailSettings 
{
        public string MailToAddress = "test@Test.com";
        public string MailFromAddress = "test@test.com";
        public bool UseSsl = true;
        public string Username = "";
        public string Password = "";
        public string ServerName = "";
        public int ServerPort = 587;
        public bool WriteAsFile = false;
        public string FileLocation = @"C:\sports_store_emails";
}

public class EmailController : Controller
{
        private IEmailRepository emailRepository;
        private EmailSettings emailSettings;

        public EmailController(IEmailRepository emailRepository, EmailSettings settings)
        {
            this.emailRepository = emailRepository;
            this.emailSettings = settings;
        }
}

public class EmailRepository : RepositoryBase<EmailEnquiry>, IEmailRepository
{
    public EmailRepository(IDatabaseFactory databaseFactory)
        : base(databaseFactory)
    {
    }
}

public interface IEmailRepository : IRepository<EmailEnquiry>
{
}

public interface IRepository<T> where T : class
{
        void Add(T entity);
        void Update(T entity);
        void Delete(T entity);      
        void Delete(Expression<Func<T, bool>> where);
        T GetById(long Id);
        T GetById(string Id);
        T Get(Expression<Func<T, bool>> where);
        IEnumerable<T> GetAll();
        IEnumerable<T> GetMany(Expression<Func<T, bool>> where);
        IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate);
}

由于某种原因,NInject设置的参数没有被传入。有谁知道这是为什么。设置是使用EmailSettings内的所有值,而不是从NInject传递的内容?

1 个答案:

答案 0 :(得分:0)

如果您已为IDatabaseFactory配置了绑定,则可以将EmailRepository创建为

var emailRepository = kernel.Get<EmailRepository>();

<强>更新

要初始化EmailController的实例,您只需使用

即可
var emailController =
          new EmailController(kernel.Get<EmailRepository>(), settings);