ServiceStack-依赖性似乎不会被注入? [英] ServiceStack - Dependency seem's to not be Injected?

查看:134
本文介绍了ServiceStack-依赖性似乎不会被注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下存储库类:

public class Repository<T> : IDisposable where T : new()
{
    public IDbConnectionFactory DbFactory { get; set; } //Injected by IOC
    IDbConnection db;
    IDbConnection Db
    {
        get
        {
            return db ?? (db = DbFactory.Open());
        }
    }

    public Repository()
    {
        Db.DropAndCreateTable<T>();
    }

    public List<T> GetByIds(long[] ids)
    {
        return Db.Ids<T>(ids).ToList();
    }
}

然后在我的AppHost.Configure()中.我这样注册依赖项:

Then in my AppHost.Configure() . I register the dependency like so:

container.Register<IDbConnectionFactory>(c => 
            new OrmLiteConnectionFactory(ConfigurationManager.
       ConnectionStrings["AppDb"].ConnectionString, SqlServerDialect.Provider));

container.RegisterAutoWired<Repository<Todo>>().ReusedWithin(Funq.ReuseScope.None);

但是,当我运行我的应用程序时,似乎我的DbFactory为null,并且在我收到Null Reference异常时未正确注入.

But when I run my application it seem's my DbFactory is null and not being injected properly as I get a Null Reference exception.

推荐答案

在尝试访问构造函数中的任何依赖项时,它将为null,因为该类是在IOC有机会注入任何依赖项之前启动的.

It's going to be null when trying to access any dependency in the constructor because the class is initiated before the IOC has a chance to inject any of the dependencies.

我会将所有初始化/设置逻辑移到AppHost.Configure()中,例如:

I would move out any initialization/setup logic into AppHost.Configure(), e.g:

using (var db = container.Resolve<IDbConnectionFactory>().Open())
{
    db.DropAndCreateTable<MyType>();
}

这篇关于ServiceStack-依赖性似乎不会被注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆