0

I would like my constructor to call another constructor with parameter but when I do this(MyProperty), then MyProperty must be static. And the problem is in the getter of this static Property, I have to get an instance of ISettingReader from structuremap Container and as it is static, my container contains only two elements instead of more than 50 elements, then it can't find the instance. (Error of pluginFamily on ISettingReader)

Here's my code.

    private static Func<LinqDataContext> _contextFactory;
    public static Func<LinqDataContext> DefaultContextFactory
    {
        get
        {
            var settingReader = ObjectFactory.GetInstance<ISettingReader>(); // I get an error saying it can't find ISettingReader()
            var connectionString = settingReader.GetSetting("MyProject.ConnectionString");
            _contextFactory = () => new LinqDataContext(connectionString);
            return _contextFactory;
        }
    }

    public MyProjectViewModelService() : this(DefaultContextFactory)
    {

    }

    public MyProjectViewModelService(Func<LinqDataContext> contextFactory)
    {
        _contextFactory = contextFactory;
    }

I think if I can get rid of my static keyword, it should work. And I confirm I have initialized my ISettingReader in structureMap container when I started my application in Program.exe

So what should I do ? Thanks !

John

PS: there's similar problem I found on stackoverflow, but he doesn't use structureMap: Constructor chaining with intermediate variables

1 Answer 1

1

Why don't you move the code from your getter to the default constructor and put the ISettingReader as a dependency in the constructor. When you request a new MyProjectViewModelService Structuremap will automatically resolve the ISettingReader and supply the instantiated default type for that dependency.

So if you would have
public MyProjectViewModelService(ISettingReader settingReader)
{
var connectionString = settingReader.GetSetting("MyProject.ConnectionString");
_contextFactory = () => new LinqDataContext(connectionString);
}

You can remove the rest.

The exception you get from structuremap is because you didn't configure any default instance for ISettingReader

Sign up to request clarification or add additional context in comments.

1 Comment

you are absolutely right. I thought I know well structuremap but actually not -_-. But thanks a lot anyway thekip, you're the god of C# development.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.