Return Yield for interface generic classes - c#

I am struggling with how to return Yield for type that is interface type of IBasic. Currently i can have three diffrent types of IBasic: InputData1, InputData2, InputData3.
The problem is on this part of code:
internal class CsvRepo<T> : ICsvRepo<T> where T : IBasic
{
private readonly ICsvSettings _settings;
public CsvRepo(ICsvSettings settings)
{
_settings = settings;
}
public IEnumerable<T> GetRecords()
{
//return from line in File.ReadLines(_settings.Path)
// select line.Split(',') into parts
// where parts.Length == 3
// select new InputData { X = Convert.ToInt32(parts[1]), Y = Convert.ToInt32(parts[2]) };
}
}
in the line: select new InputData
i am going to say something like return new IBasic but diffrent InputDataX has diffrent parameters and i am not sure how to do so? Is it possible?
This is full code:
namespace ClassLibrary3
{
public interface IRepo { }
public interface IRepository<T> : IRepo where T : IBasic { }
public interface ICsvRepo<T> : IRepository<T> where T : IBasic
{
IEnumerable<T> GetRecords();
}
public interface ISqlRepo
{
}
public interface IOracleRepo<T> : IRepository<T> where T : IBasic { }
public interface IRepoX : IRepo { }
public interface ICsvSettings
{
string Path { get; }
string FileName { get; }
}
public interface ISqlSettings
{
string ConnectionString { get; }
string Username { get; }
string Password { get; }
}
internal class CsvSettings : ICsvSettings
{
public string Path { get; set; }
public string FileName { get; set; }
}
internal class SqlSettings : ISqlSettings
{
public string ConnectionString { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
internal class CsvRepo<T> : ICsvRepo<T> where T : IBasic
{
private readonly ICsvSettings _settings;
public CsvRepo(ICsvSettings settings)
{
_settings = settings;
}
public IEnumerable<T> GetRecords()
{
return null;
//return from line in File.ReadLines(_settings.Path)
// select line.Split(',') into parts
// where parts.Length == 3
// select new InputData { X = Convert.ToInt32(parts[1]), Y = Convert.ToInt32(parts[2]) };
}
}
internal class SqlRepo : ISqlRepo
{
private readonly ISqlSettings _settings;
private readonly IRepoX _repoX;
public SqlRepo(ISqlSettings settings, IRepoX repoX)
{
_settings = settings;
_repoX = repoX;
}
}
internal class OracleRepo<T> : IOracleRepo<T> where T : IBasic
{
private readonly ISqlSettings _settings;
private readonly IRepoX _repoX;
public OracleRepo(ISqlSettings settings, IRepoX repoX)
{
_settings = settings;
_repoX = repoX;
}
}
internal class OracleRepo333<T> : IOracleRepo<T> where T : IBasic
{
private readonly ISqlSettings _settings;
private readonly IRepoX _repoX;
public int id;
public OracleRepo333(ISqlSettings settings, IRepoX repoX)
{
_settings = settings;
_repoX = repoX;
}
}
internal class RepoX : IRepoX { }
public class RepoModule : NinjectModule
{
private readonly string _username;
private readonly string _password;
public RepoModule(string username, string password)
{
_username = username;
_password = password;
}
public override void Load()
{
Bind<ICsvSettings>().ToConstant(new CsvSettings
{
FileName = "foo",
Path = Config.Instance.ServerName,
}).InSingletonScope();
Bind<ISqlSettings>().ToConstant(new SqlSettings
{
ConnectionString = "foo",
Password = _password,
Username = _username
}).InSingletonScope();
Bind<IRepoX>().To<RepoX>();
Bind(typeof(ICsvRepo<>)).To(typeof(CsvRepo<>));
Bind(typeof(ISqlRepo)).To(typeof(SqlRepo));
Bind(typeof(IOracleRepo<>)).To(typeof(OracleRepo<>));
Bind(typeof(IOracleRepo<>)).To(typeof(OracleRepo333<>));
}
}
public interface IBasic
{
}
public class InputData1 : IBasic
{
public int X;
public int Y;
}
public class InputData2 : IBasic
{
public string Name;
}
public class InputData3 : IBasic
{
public IEnumerable<string> WhateverList;
}
}
class Program
{
static void Main(string[] args)
{
var kernel = new StandardKernel(new RepoModule("foo", "bar")); /*some other modules here maybe?*/
//thousand of code lines later...
var csvRepo = kernel.Get<ICsvRepo<InputData1>>();
//var data = FetchData(csvRepo);
var sqlRepo = kernel.Get<ISqlRepo>();
//data = FetchData(sqlRepo);
// var oracleRepo = kernel.Get<IOracleRepo<InputData>>();
//data = FetchData(oracleRepo);
var oracleRepos = kernel.GetAll<List<IOracleRepo<InputData1>>>();}
}
}
//static T[] FetchData<T>(IRepository<InputData> repo)
//{
// throw new NotImplementedException();
//}
}

The problem is that you are trying to return a concrete type where a generic type is expected. Consider the following instantiation of CsvRepo<T>
var repo = new CsvRepo<InputData1Derived>(null);
repo.GetRecords().First().PropFromInputData1Derived
You are instantiating InputData while the caller expects InputDataDerived. This is why the compiler does not let you do this.
You could have several solutions, let CsvRepo could be abstract and implement it for specific classes:
internal abstract class CsvRepo<T> : ICsvRepo<T> where T : IBasic
{
public CsvRepo()
{
}
public abstract IEnumerable<T> GetRecords();
}
internal class InputDataCsvRepo : CsvRepo<InputData1>
{
public override IEnumerable<InputData1> GetRecords()
{
return from line in File.ReadLines(_settings.Path)
select line.Split(',') into parts
where parts.Length == 3
select new InputData { X = Convert.ToInt32(parts[1]), Y = Convert.ToInt32(parts[2]) };
}
}
Or you can make the T parameter have a default constructor and use that (but only properties in IBasic will be initializable which is not what you want probably.

This seems to be one of those situations where if you have a hammer everything looks like a nail. In short there is no need to make the argument for the method generic as already know the concrete return type for any implementation and you want that return type to implement a specific interface.
Remove the generic type constraint T on method GetRecords and replace it with IBasic interface constraint.
public interface ICsvRepo<T> : IRepository<T> where T : IBasic
{
IEnumerable<IBasic> GetRecords();
}
internal class CsvRepo<T> : ICsvRepo<T> where T : IBasic
{
private readonly ICsvSettings _settings;
public CsvRepo(ICsvSettings settings)
{
_settings = settings;
}
public IEnumerable<IBasic> GetRecords()
{
return from line in File.ReadLines(_settings.Path)
select line.Split(',') into parts
where parts.Length == 3
select new InputData { X = Convert.ToInt32(parts[1]), Y = Convert.ToInt32(parts[2]) };
}
}
I altered your code below to only include what is needed to show the solution.
On an unrelated note making fields public is almost always a bad idea because you expose the internals of the class. Make them into properties instead with public getter/setters.
Example:
public class InputData : IBasic
{
public int X {get;set;}
public int Y {get;set;}
}

Related

C# setting property to interface class using dependency injection

I have the following class that implements dependency injection for ISecurityRepository:
public class SecurityService : BaseService
{
ISecurityRepository _securityRepo = null;
public SecurityService(ISecurityRepository securityRepo)
{
_securityRepo = securityRepo;
}
}
Then I have the SecurityRepository class as follows:
public class SecurityRepository : BaseRepository, ISecurityRepository
{
public bool ValidateLogin(string userName, string password)
{
return true;
}
}
Then BaseRepository class:
public abstract class BaseRepository
{
private string _customString = null;
public string CustomString{
get {
return _customString ;
}
set
{
value = _customString ;
}
}
}
What I need is to set CustomString on BaseRepository class value from SecurityService class. Something maybe like this:
public class SecurityService : BaseService
{
ISecurityRepository _securityRepo = null;
public SecurityService(ISecurityRepository securityRepo)
{
_securityRepo = securityRepo;
// something like this or better way
_securityRepo.CustomString = "ABCD";
}
}
The idea is that within SecurityRepository class I can access CustomString value.

Fluent Builder pattern which returns root type

I want to create builder for my purpose, with such call chain:
User user = new CommonBuilder(new UserNode()).Root //generic parameter, currently is User
.Group.Group.Folder.Build();
Here is the code, which I use:
public abstract class AbstractNode
{
public Guid Id { get; } = Guid.NewGuid();
}
public abstract class AbstractNode<T> where T : AbstractNode<T>
{
}
public class CommonBuilder<T> where T : AbstractNode<T>
{
public T Root { get; private set; }
public CommonBuilder(T root)
{
Root = root;
}
}
public class UserNode : AbstractNode<UserNode>
{
private GroupNode _group;
public GroupNode Group
{
get
{
if (_group is null)
{
_group = new GroupNode();
}
return _group;
}
}
}
public class GroupNode : AbstractNode<GroupNode>
{
private GroupNode _group;
public GroupNode Group
{
get
{
if (_group is null)
{
_group = new GroupNode();
}
return _group;
}
}
private FolderNode _folder;
public FolderNode Folder
{
get
{
if (_folder is null)
{
_folder = new FolderNode();
}
return _folder;
}
}
}
public class FolderNode : AbstractNode<FolderNode>
{
}
The problem is in the Build() method, which need to return Root from CommonBuilder, not the File.
Where must I place Build() method, which must be always called at the end of a chain, which returns Root of a builder?
In case when it's required to make a chain the same object should be returned, even as another interface check first and second examples of implementation Builder with Fluent intefaces
I've tried to implement your case to fit the role, check if it will fits your requirements:
public interface IGroup<T>
{
IGroup<T> Group { get; }
IFolder<T> Folder { get; }
}
public interface IFolder<T>
{
T Build();
}
Builder implements all required interfaces. And returns itself in each call. In general you can put Build method in the builder itself and call it separately after the end of chain execution.
public class CommonBuilder<T> : IGroup<T>, IFolder<T> where T: INode, new()
{
private T _root = new T();
public T Build()
{
return _root;
}
public IGroup<T> Group
{
get
{
_root.MoveToGroup();
return this;
}
}
public IFolder<T> Folder
{
get
{
_root.MoveToFolder();
return this;
}
}
}
Because of generics it's required to set some limitations on generic parameter which is done with INode interface
public interface INode
{
void MoveToGroup();
void MoveToFolder();
}
Testing user object
public class User : INode
{
public StringBuilder Path { get; } = new StringBuilder();
public void MoveToFolder()
{
Path.AppendLine("Folder");
}
public void MoveToGroup()
{
Path.AppendLine("Group");
}
public override string ToString()
{
return Path.ToString();
}
}
And the call will looks like
var user = new CommonBuilder<User>().Group.Group.Folder.Build();
EDIT
Maybe as a the first stage it makes sence to get rid of Fluent interfaces and implement logic using just a Builder:
public class FolderNode : INode<Folder>
{
private readonly Folder _folder = new Folder();
public Folder Build()
{
return _folder;
}
public void AppendGroup()
{
_folder.Path.AppendLine("Folder Group");
}
public void AppendFolder()
{
_folder.Path.AppendLine("Folder Folder");
}
}
public class UserNode : INode<User>
{
private readonly User _user = new User();
public User Build()
{
return _user;
}
public void AppendGroup()
{
_user.Path.AppendLine("Group");
}
public void AppendFolder()
{
_user.Path.AppendLine("Folder");
}
}
public class CommonBuilder<T, TNode> where TNode : INode<T>
{
private readonly TNode _root;
public CommonBuilder(TNode root)
{
_root = root;
}
public T Build()
{
return _root.Build();
}
public CommonBuilder<T, TNode> Group {
get
{
_root.AppendGroup();
return this;
}
}
public CommonBuilder<T, TNode> Folder {
get
{
_root.AppendFolder();
return this;
}
}
}
public interface INode<out T>
{
T Build();
void AppendGroup();
void AppendFolder();
}
public class Folder
{
public StringBuilder Path { get; } = new StringBuilder();
public override string ToString()
{
return Path.ToString();
}
}
public class User
{
public StringBuilder Path { get; } = new StringBuilder();
public override string ToString()
{
return Path.ToString();
}
}
Usage:
var user = new CommonBuilder<User, UserNode>(new UserNode()).Group.Group.Folder.Build();
var folder = new CommonBuilder<Folder, FolderNode>(new FolderNode()).Group.Folder.Group.Folder.Build();

Inject an unknown value at registration time with Unity

Here the Unity registration
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
container.RegisterType<ITestService,TestService>(new InjectionConstructor("XXXXX"));
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
}
Here the webApi controller
[MyFilter]
public class TestController : ApiController
{
private ITestService _testService;
public EmployeeController(ITestService testService)
{
_testService = testService;
}
}
My test class
public interface ITestService
{
string GetText();
}
public class TestService : ITestService
{
private string _mystring;
public TestService(string mystring)
{
_mystring = mystring;
}
public string GetText()
{
return _mystring;
}
}
The problem : The value to inject in the constructor (hard coded here "XXXXX")is know only in [MyFilter] not before, not at registration time. Is it possible to inject a value coming from the attribute ?
Thanks,
Update1:
The workaround I used is save the value "XXXXX" in session working but not very clean.
public class MyFilter: AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
try
{
HttpContext.Current.Session["MyData"] = "XXXXX";
return;
HandleUnauthorized(actionContext);
}
catch (Exception ex)
{
}
}
private void HandleUnauthorized(HttpActionContext actionContext)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
Inject value in resolve method:
container.RegisterType<ITestService,TestService>();
...
var service = container.Resolve<ITestService>(new ParameterOverride(#"mystring", new InjectionParameter(typeof(string), "XXXXX")));
Expanding on my comment above, this example shows a way of storing the filter value in an attribute and recovering it to pass it into the TestService:
This assumes that each TestController will use the same filter (here abc), and that each OtherTestController will use the same other filter (like, def ?). That is, the filter attached to the type not the instance.
class Program
{
static void Main( string[] args )
{
var unityContainer = new UnityContainer();
unityContainer.RegisterType<ITestServiceFactory, TestServiceFactory>();
var theController = unityContainer.Resolve<TestController>();
// theController._testService.FilterString is "abc"
}
}
[MyFilter("abc")]
public class TestController
{
private ITestService _testService;
public TestController( ITestServiceFactory testServiceFactory )
{
_testService = testServiceFactory.CreateTestService(this);
}
}
public class MyFilterAttribute : Attribute
{
public string FilterString
{
get;
}
public MyFilterAttribute( string filterString )
{
FilterString = filterString;
}
}
public interface ITestServiceFactory
{
ITestService CreateTestService( object owner );
}
public interface ITestService
{
string GetText();
}
internal class TestServiceFactory : ITestServiceFactory
{
public ITestService CreateTestService( object owner )
{
return new TestService( ((MyFilterAttribute)owner.GetType().GetCustomAttribute( typeof( MyFilterAttribute ) )).FilterString );
}
}
internal class TestService : ITestService
{
public TestService( string mystring )
{
_mystring = mystring;
}
public string GetText()
{
return _mystring;
}
private readonly string _mystring;
}
If you don't insist on the attribute, you can simplify this and set the filter in TestController's constructor directly:
public TestController( ITestServiceFactory testServiceFactory )
{
_testService = testServiceFactory.CreateTestService("abc");
}

Is there a way to make C# generics handle this scenario

When having the following scenario I am unhappy with the consuming code that is littered with the line
var queryResult = _queryDispatcher.Dispatch<CustomerByIdQuery, CustomerByIdQueryResult>(customerByIdQuery).Customer;
I would prefer to have the code work this way for the consumer:
var queryResult = _queryDispatcher.Dispatch(customerByIdQuery).Customer;
Is there a way to accomplish this using generics?
Here is the code
interface IQuery{}
interface IQueryResult{}
interface IQueryHandler<TQuery, TQueryResult> : where TQueryResult:IQueryResult where TQuery:IQuery
{
TQueryResult Execute(TQuery query);
}
interface IQueryDispatcher
{
TQueryResult Dispatch<TQuery, TQueryResult>(TQuery query) where TQuery:IQuery where TQueryResult:IQueryResult
}
class GenericQueryDispatcher : IQueryDispatcher
{
public TQueryResult Dispatch<TQuery, TQueryResult>(TQuery parms)
{
var queryHandler = queryRegistry.FindQueryHandlerFor(TQuery);
queryHandler.Execute
}
}
class CustomerByIdQuery : IQuery
{
public int Id { get; set; }
}
class CustomerByIdQueryResult : IQueryResult
{
public Customer {get; set;}
}
class CustomerByIdQueryHandler : IQueryHandler
{
public CustomerByIdQueryResult Execute(TQuery query)
{
var customer = _customerRepo.GetById(query.Id);
return new CustomerByIdQueryResult(){Customer = customer};
}
}
public class SomeClassThatControlsWorkFlow
{
IQueryDispatcher _queryDispatcher;
public SomeClassThatControlsWorkFlow(IQueryDispatcher queryDispatcher)
{
_queryDispatcher = queryDispatcher;
}
public void Run()
{
var customerByIdQuery = new CustomerByIdQuery(){Id=1};
//want to change this line
var customer = _queryDispatcher.Dispatch<CustomerByIdQuery, CustomerByIdQueryResult>(customerByIdQuery).Customer;
}
}
Here is what I would like to have :
public class ClassWithRunMethodIWouldLikeToHave
{
IQueryDispatcher _queryDispatcher;
public SomeClassThatControlsWorkFlow(IQueryDispatcher queryDispatcher)
{
_queryDispatcher = queryDispatcher;
}
public void Run()
{
var customerByIdQuery = new CustomerByIdQuery(){Id=1};
//want to change this line
var customer = _queryDispatcher.Dispatch(customerByIdQuery).Customer;
}
}
Yes, it's possible, but you have to make the Dispatch method's parameter generic (that way, the compiler can infer the type parameters from the method parameter). To do this, it looks like you'll first need a generic version of the IQuery and IQueryResult interfaces:
interface IQuery<TQuery, TQueryResult> : IQuery {}
interface IQueryResult<T> : IQueryResult
{
T Result { get; }
}
Next, make CustomerByIdQuery and CustomerByIdQueryResult implement the respective generic interfaces:
class CustomerByIdQuery : IQuery, IQuery<int, Customer>
{
public int Id { get; set; }
}
class CustomerByIdQueryResult : IQueryResult, IQueryResult<Customer>
{
public Customer Result {get; set;}
}
Now you can add an overload for Dispatch that accepts the generic parameter:
interface IQueryDispatcher
{
IQueryResult<TQueryResult> Dispatch<TQuery, TQueryResult>(IQuery<TQuery, TQueryResult> parms);
}
class GenericQueryDispatcher : IQueryDispatcher
{
public TQueryResult Dispatch<TQuery, TQueryResult>(IQuery<TQuery, TQueryResult> parms)
{
// TODO implement
}
}
The above will allow you to write:
var customerByIdQuery = new CustomerByIdQuery{Id=1};
var customer = _queryDispatcher.Dispatch(customerByIdQuery).Result;
I can't get rid of the cast, but this is working pretty close to what I want.
public interface IQueryDispatcher
{
TQueryResult Dispatch<TParameter, TQueryResult>(IQuery<TQueryResult> query)
where TParameter : IQuery<TQueryResult>
where TQueryResult : IQueryResult;
}
public interface IQueryHandler<in TQuery, out TQueryResult>
where TQuery : IQuery<TQueryResult>
where TQueryResult : IQueryResult
{
TQueryResult Retrieve(TQuery query);
}
public interface IQueryResult { }
public interface IQuery { }
public interface IQuery<TQueryResult> : IQuery { }
public class QueryDispatcher : IQueryDispatcher
{
readonly IQueryHandlerRegistry _queryRegistry;
public QueryDispatcher(IQueryHandlerRegistry queryRegistry)
{
_queryRegistry = queryRegistry;
}
public TQueryResult Dispatch<TQuery, TQueryResult>(IQuery<TQueryResult> query)
where TQuery : IQuery<TQueryResult>
where TQueryResult : IQueryResult
{
var handler = _queryRegistry.FindQueryHandlerFor<TQuery, TQueryResult>(query);
//CANT GET RID OF CAST
return handler.Retrieve((TQuery)query);
}
}
public interface IQueryHandlerRegistry
{
IQueryHandler<TQuery, TQueryResult> FindQueryHandlerFor<TQuery, TQueryResult>(IQuery<TQueryResult> query)
where TQuery : IQuery<TQueryResult>
where TQueryResult : IQueryResult;
}
public class GetCustByIdAndLocQuery : IQuery<CustByIdAndLocQueryResult>
{
public string CustName { get; set; }
public int LocationId { get; set; }
public GetCustByIdAndLocQuery(string name, int locationId)
{
CustName = name;
LocationId = locationId;
}
}
public class CustByIdAndLocQueryResult : IQueryResult
{
public Customer Customer { get; set; }
}
public class GetCustByIdAndLocQueryHandler : IQueryHandler<GetCustByIdAndLocQuery, CustByIdAndLocQueryResult>
{
readonly ICustomerGateway _customerGateway;
public GetCustByIdAndLocQueryHandler(ICustomerGateway customerGateway)
{
_customerGateway = customerGateway;
}
public CustByIdAndLocQueryResult Retrieve(GetCustByIdAndLocQuery query)
{
var customer = _customerGateway.GetAll()
.SingleOrDefault(x => x.LocationId == query.LocationId && x.CustomerName == query.CustName);
return new CustByIdAndLocQueryResult() { Customer = customer };
}
}
public interface ICustomerGateway
{
IEnumerable<Customer> GetAll();
}
public class Customer
{
public string CustomerName { get; set; }
public int LocationId { get; set; }
public bool HasInsurance { get; set; }
}

How to code a good Offline-Online Dispatcher

Let's assume that I have this scenario: I have got 2 repositories of information, and I want to access both, but it would be nice to leave the task of deciding which repo to use to common class.
The goal is to accomplish this with something similar to the code I've wrote below, but this sounds pretty bad:
where TOnline : class
where TOffline : class
where TContract : class
Sure I can ommit that, but bassically what I'm asking is what to do in order to stop using reflection and go typed. Maybe any design-pattern recomendation?
Code (if you copy/paste this on a console app replacing the Program class you should be able to run the example)
using CustomerDispatcher = DispatcherProxy<CustomerOnline, CustomerOffline, ICustomer>;
public interface ICustomer
{
string Get(int id);
}
public class CustomerOnline : ICustomer
{
public string Get(int id)
{
// Get From intranet DB
return "From DB";
}
}
public class CustomerOffline : ICustomer
{
public string Get(int id)
{
// Get From local storage
return "From local storage";
}
}
public class DispatcherProxy<TOnline, TOffline, TContract>
where TOnline : class
where TOffline : class
where TContract : class
{
public TContract Instance { get; set; }
public bool IsConnected { get; set; }
public DispatcherProxy()
{
// Asume that I check if it's connected or not
if (this.IsConnected)
this.Instance = (TContract)Activator.CreateInstance(typeof(TOnline));
else
this.Instance = (TContract)Activator.CreateInstance(typeof(TOffline));
}
}
class Program
{
static void Main(string[] args)
{
var customerDispatcher = new CustomerDispatcher();
Console.WriteLine("Result: " + customerDispatcher.Instance.Get(1));
Console.Read();
}
}
Thanks in advance!
You can add the new() constraint:
public class DispatcherProxy<TOnline, TOffline, TContract>
where TOnline : class, new()
where TOffline : class, new()
where TContract : class //isn't TContract an interface?
{
public TContract Instance { get; set; }
public bool IsConnected { get; set; }
public DispatcherProxy()
{
// Asume that I check if it's connected or not
if (this.IsConnected)
this.Instance = new TOnline() as TContract;
else
this.Instance = new TOffline() as TContract;
}
}
In case any of you are interested, I had to change the way I did this because it was checking connection at Constructor Level, and I needed that check at Operation Level.
using System;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.InterceptionExtension;
namespace ConsoleApplication1
{
public enum ConnectionStatus
{
Online,
Offline,
System // System checks connectivity
}
public static class Connectivity
{
private static ConnectionStatus ConnectionStatus = ConnectionStatus.Offline;
public static void ForceConnectionStatus(ConnectionStatus connectionStatus)
{
ConnectionStatus = connectionStatus;
}
public static bool IsConnected()
{
switch (ConnectionStatus)
{
case ConnectionStatus.Online:
return true;
case ConnectionStatus.Offline:
return false;
case ConnectionStatus.System:
return CheckConnection();
}
return false;
}
private static bool CheckConnection()
{
return true;
}
}
public class Unity
{
public static IUnityContainer Container;
public static void Initialize()
{
Container = new UnityContainer();
Container.AddNewExtension<Interception>();
Container.RegisterType<ILogger, OnlineLogger>();
Container.Configure<Interception>().SetInterceptorFor<ILogger>(new InterfaceInterceptor());
}
}
class Program
{
static void Main(string[] args)
{
Unity.Initialize();
var r = new Router<ILogger, OnlineLogger, OnlineLogger>();
Connectivity.ForceConnectionStatus(ConnectionStatus.Offline);
Console.WriteLine("Calling Online, will attend offline: ");
r.Logger.Write("Used offline.");
Connectivity.ForceConnectionStatus(ConnectionStatus.Online);
Console.WriteLine("Calling Online, will attend online: ");
r.Logger.Write("Used Online. Clap Clap Clap.");
Console.ReadKey();
}
}
public class Router<TContract, TOnline, TOffline>
where TOnline : TContract
where TOffline : TContract
{
public TContract Logger;
public Router()
{
Logger = Unity.Container.Resolve<TContract>();
}
}
public interface IOnline
{
IOffline Offline { get; set; }
}
public interface IOffline
{
}
public interface ILogger
{
[Test()]
void Write(string message);
}
public class OnlineLogger : ILogger, IOnline
{
public IOffline Offline { get; set; }
public OnlineLogger()
{
this.Offline = new OfflineLogger();
}
public void Write(string message)
{
Console.WriteLine("Online Logger: " + message);
}
}
public class OfflineLogger : ILogger, IOffline
{
public IOnline Online { get; set; }
public void Write(string message)
{
Console.WriteLine("Offline Logger: " + message);
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
public class TestAttribute : HandlerAttribute
{
public override ICallHandler CreateHandler(IUnityContainer container)
{
return new TestHandler();
}
}
public class TestHandler : ICallHandler
{
public int Order { get; set; }
public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
{
Console.WriteLine("It's been intercepted.");
if (!Connectivity.IsConnected() && input.Target is IOnline)
{
Console.WriteLine("It's been canceled.");
var offline = ((input.Target as IOnline).Offline);
if (offline == null)
throw new Exception("Online class did not initialized Offline Dispatcher.");
var offlineResult = input.MethodBase.Invoke(offline, this.GetObjects(input.Inputs));
return input.CreateMethodReturn(offlineResult, this.GetObjects(input.Inputs));
}
return getNext()(input, getNext);
}
private object[] GetObjects(IParameterCollection parameterCollection)
{
var parameters = new object[parameterCollection.Count];
int i = 0;
foreach (var parameter in parameterCollection)
{
parameters[i] = parameter;
i++;
}
return parameters;
}
}
}

Categories

Resources