Unity
// ui
public class DIController : ApiController
{
/*
-> techniq that helps to inject dependant objects to the class.
-> why di
-> reduce tide cupling. and be a losely cuple archi.
-> core of decuppling in two layers are interface.
*/
private ICustomer cus;
public DIController(ICustomer _cus) {
cus = _cus;
}
[HttpGet]
public string Add()
{
cus.Add();
return "added";
}
}
// bl
public interface ICustomer {
void Add();
}
public class Customer:ICustomer
{
public string CustomerName { get; set; }
private IDal obj;
public Customer(IDal iobj)
{
obj = iobj;
}
public void Add()
{
obj.Add();
}
}
// dal
public interface IDal
{
void Add();
}
public class SqlDal : IDal
{
public void Add()
{
Console.WriteLine("recode inserted to sql server");
}
}
public class OracleDal : IDal
{
public void Add()
{
Console.WriteLine("recode inserted to oracle server");
}
}
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var container = new UnityContainer();
container.RegisterType<IDal, SqlDal>(new HierarchicalLifetimeManager());
container.RegisterType<IDal, OracleDal>(new HierarchicalLifetimeManager());
container.RegisterType<ICustomer, Customer>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
}
}
///////////////////////////////////////////////////
namespace DependancyInjections.App_Start
{
public class UnityResolver : IDependencyResolver
{
protected IUnityContainer container;
public UnityResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}
public IDependencyScope BeginScope()
{
var child = container.CreateChildContainer();
return new UnityResolver(child);
}
public void Dispose()
{
container.Dispose();
}
}
}
No comments:
Post a Comment