private IProductRepository _productRepository;
private IProductRepository ProductRepository
{
get
{
if (_productRepository == null )
{
_productRepository = new ProductRepository();
}
return _productRepository;
}
}
* This source code was highlighted with Source Code Highlighter .
private IProductRepository _productRepository;
private IProductRepository ProductRepository
{
get
{
if (_productRepository == null )
{
_productRepository = ObjectFactory.GetInstance<IProductRepository>();
}
return _productRepository;
}
}
* This source code was highlighted with Source Code Highlighter .
[LoadDependency] private IProductRepository _productRepository;
[ Serializable ]
public sealed class LoadDependencyAttribute : LocationInterceptionAspect
{
public override void OnGetValue(LocationInterceptionArgs args)
{
args.ProceedGetValue(); // fetches the field and populates the args.Value
if (args.Value == null )
{
var locationType = args.Location.LocationType;
var instantiation = ObjectFactory.GetInstance(locationType);
if (instantiation != null )
{
args.SetNewValue(instantiation);
}
args.ProceedGetValue();
}
}
}
* This source code was highlighted with Source Code Highlighter .
[ Serializable ]
public sealed class LoadDependencyAttribute : LocationInterceptionAspect
{
private Type _type;
public override bool CompileTimeValidate(PostSharp.Reflection.LocationInfo locationInfo)
{
_type = DependencyMap.GetConcreteType(locationInfo.LocationType);
if (_type == null )
{
Message.Write(SeverityType.Error, "002" ,
"A concrete type was not found for {0}.{1}" ,
locationInfo.DeclaringType, locationInfo.Name);
return false ;
}
return true ;
}
public override void OnGetValue(LocationInterceptionArgs args)
{
args.ProceedGetValue();
if (args.Value == null )
{
form.LogListBox.Items.Add( "Instantiating UserService" );
args.SetNewValue(Activator.CreateInstance(_type));
args.ProceedGetValue();
}
}
}
* This source code was highlighted with Source Code Highlighter .
public override bool CompileTimeValidate(PostSharp.Reflection.LocationInfo locationInfo)
{
if (!locationInfo.LocationType.IsInterface)
{
Message.Write(SeverityType.Error, "001" ,
"LoadDependency can only be used on Interfaces in {0}.{1}" ,
locationInfo.DeclaringType, locationInfo.Name);
return false ;
}
_type = DependencyMap.GetConcreteType(locationInfo.LocationType);
if (_type == null )
{
Message.Write(SeverityType.Error, "002" ,
"A concrete type was not found for {0}.{1}" ,
locationInfo.DeclaringType, locationInfo.Name);
return false ;
}
return true ;
}
* This source code was highlighted with Source Code Highlighter .
Source: https://habr.com/ru/post/125098/