How to assign default value to a property

删除回忆录丶 提交于 2019-12-02 04:00:45

Be sure to include all relevant info and context about your question as this would be impossible to infer without out-of-hand knowledge on how you're using it. E.g. what does your IOC look like?

You're asking for an IDbConnection in your constructor:

public CustomerService(IDBConnection dbConnection)
{
     SelectCommand = new ServiceCommand();
}

But it's very likely you're only registering an IDbConnectionFactory, so there doesn't exist any registered dependency with IDbConnection.

If you inheriting from Service class you've already got the IDbConnectionFactory injected and access to the IDbConnection with the base.Db property:

private IDbConnection db;
public virtual IDbConnection Db
{
    get { return db ?? (db = TryResolve<IDbConnectionFactory>().Open()); }
}

All public properties get injected by the IOC

The reason why SelectCommand property is null is because it's a public property. All of your Services public properties are attempted to be resolved by your Registered dependencies and because you don't have any registered dependencies of type ServiceCommand it is overrided with null. If this was defined in your constructor instead it would've thrown a run-time exception, because it's just a property it's initialized to null.

If you change the visibility of SelectCommand to protected, private, internal or static it wont be attempted to be injected by the IOC.

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