ServiceStack - Dependency seem's to not be Injected?

南笙酒味 提交于 2019-12-05 02:48:35

问题


I have the following repository class:

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();
    }
}

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);

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.


回答1:


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.

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

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


来源:https://stackoverflow.com/questions/14486462/servicestack-dependency-seems-to-not-be-injected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!