Microsoft Enterprise Library
Raja introduced us to Microsoft Enterprise Library via five examples:
- Dependency Injection
- Exception Handling
- Logging
- Caching
- Validation
To me, the best part was that the app.config file can be edited visually making it a straightforward matter to modify logging, exception handling and validation rules. Russell pointed out that this is an example of Aspect Oriented Programming which allows for the separation of cross-cutting concerns.
Dependency Injection was demonstrated via a UnityContainer which acts as a sort of factory to produce an instance of RateTable containing a strategy:
The specific strategy is specified in the app.config:
using (IUnityContainer container = new UnityContainer())
{
container.LoadConfiguration();
var rt = container.Resolve();
rt.Calculate();
}
The specific strategy is specified in the app.config:
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<container>
<register type="IRateAlgorithm" mapTo="FlatRate"/>
</container>
</unity>
Exception Handling requires an ExceptionManager instance:
exManager = EnterpriseLibraryContainer.Current.GetInstance();
catch ( Exception e) exManager.HandleException(e, "BillRun");
Without the Enterprise Library Configuration Editor installed on my machine it's difficult to describe the app.config, but essentially it maps "BillRun" exceptions (a policy) through a exception type to an exception handler allowing logging, substitution and custom handling of the exception.
Logging is very similar to exceptions. A LogWriter instance is required. Also, a LogEntry object further clarifies the message category:
private LogWriter writer = EnterpriseLibraryContainer.Current.GetInstance();
public void DoLogging()
{
LogEntry log = new LogEntry();
log.Message = "Delinquency Run Starting....";
log.Categories.Add(Category.General);
log.Categories.Add(Category.BillRun);
log.Priority = Priority.Normal;
writer.Write(log);
}
Caching contains too much code...skipping
Validation requires a ValidatorFactory to create a specific validator:
Validation and ValidationResult:
At a minimum using
valFactory = EnterpriseLibraryContainer.Current.GetInstance();
customerValidator = valFactory.CreateValidator();
Validation and ValidationResult:
ValidationResults results = customerValidator.Validate(customer);
if (!results.IsValid)
{
StringBuilder builder = new StringBuilder();
builder.AppendLine("Customer is not valid:");
foreach (ValidationResult result in results)
{
//do stuff
}
}
Microsoft.Practices.EnterpriseLibrary give guidance for basic coding practices.
No comments:
Post a Comment