Вопрос

I'm using some Autofac modules to initialize config files. E.g.:

public class Config()
{
  public String ConnectionString { get; set; }
}

Regarding XML configuration everything looks like:

 <Autofac defaultAssembly="Autofac">
   <components>
     <component type="Autofac.Configuration.Config, Autofac" instance-scope="single-instance" >
       <properties>
         <property name="ConnectionString" value="Cnstring" />
       </properties>
     </component>
   </components>
 </Autofac>

I'm using this configuration to have Configuration, but in order to make it immutable I use a private setter {get; private set;}. This doesn't works in Autofac, can you please advise how should use private setter initialization?

Это было полезно?

Решение

In addition to Peter's answer, if you want to stay with property and property injection, you can add "immutability" manually by code, something like that:

public class Config
{
    private string _connectionString;

    public String ConnectionString
    {
        get
        {
            return _connectionString;
        }
        set
        {
            if (_connectionString != null) throw new ReadOnlyException("_connectionString");
            if (value == null) throw new ArgumentNullException("value");

            _connectionString = value;
        }
    }
}

Другие советы

As long as the property is read-only, Autofac will not be able to initialize it via property injection. You should use constructor injection instead in this case.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top