문제

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