Following i have a worker class and there is a foreach.
Inside the forach there is service call which can be GetX(), GetY() ...
as implementation, I have to re-initialize the Api client based on the parameter, is there pattern to avoid _aService.SetApiClient(p) Line?
public class Worker
{
private readonly IAService _aService;
public Worker(IAService entryPointService)
{
_aService = entryPointService;
}
protected void ExecuteAsync()
{
while (true)
{
new List<string>() { "x", "y", "z" }.ForEach(p =>
{
_aService.SetApiClient(p);
_aService.GetX();
// OR _aService.GetY(),_aService.GetYZ();//
});
}
}
}
public class AService : IAService
{
private GoogleApiClient _googleApiClient;
public AService(GoogleApiClient apiClient)
{
_googleApiClient = apiClient;
}
public void SetApiClient(string param)
{
_googleApiClient = new GoogleApiClient(new AuthProvider (param));
}
public string GetX()
{
return _googleApiClient.CallX();
}
}
public interface IAService
{
void SetApiClient(string param);
string GetX();
}
public interface IGoogleApiClient
{
string CallX();
string CallY();
string CallZ();
}
public class GoogleApiClient : IGoogleApiClient
{
private AuthProvider _param;
public GoogleApiClient(AuthProvider param)
{
_param = param;
}
public string CallX()
{
return DoSomeCal("X", _param);
}
public string CallY()
{
return DoSomeCal("Y", _param);
}
public string CallZ()
{
return DoSomeCal("Z", _param)
}
}
please note that string list values can be any thing
Your api client really doesn't need to hold state.(private field}) It is a service / gateway class. Rather just pass param into the methods e.g.GetX(string param}.
Related
I have this object structure
public interface IHandler<in TMessage>
{
void HandleMessage(TMessage messageType);
}
public class MessageType1
{
}
public class MessageType2
{
}
public class HandlerMessageType1 : IHandler<MessageType1>
{
public void HandleMessage(T messageType)
{
}
}
public class HandlerMessageType2 : IHandler<MessageType2>
{
public void HandleMessage(T messageType)
{
}
}
and the registration
container.Collection.Register(typeof(IHandler<>), new[]
{
typeof(HandlerMessageType1),
typeof(HandlerMessageType2)
});
how the constructor of the class where this is injected should look like?
public class ClientClass
{
public ClientClass(IEnumerable<IHandler<>> handlers)
{
}
}
like this doesn't work... how the signature of the client class constructor should look like?
this was edited to improve the example.
tkx in advance
Paulo Aboim Pinto
I Know if I understood, but with unity you can have:
public class Handler1 : IHandler
{
public void HandlerType()
{
Console.WriteLine("Handler1");
}
}
public class Handler2 : IHandler
{
public void HandlerType()
{
Console.WriteLine("Handler2");
}
}
public interface IHandler
{
void HandlerType();
}
Unity configuration
public static class DependencyConfiguration
{
public static UnityContainer Config()
{
var unity = new UnityContainer();
unity.RegisterType<IHandler, Handler1>("Handler1");
unity.RegisterType<IHandler, Handler2>("Handler2");
unity.RegisterType<IEnumerable<IHandler>>();
return unity;
}
}
A class to resolve:
public class ListOfTypes
{
private List<IHandler> handlers;
public ListOfTypes(IEnumerable<IHandler> handlers)
{
this.handlers = handlers.ToList();
}
public void PrintHandlers()
{
handlers.ForEach(_ => _.HandlerType());
}
}
The program:
static void Main(string[] args)
{
Console.WriteLine("Resolve sample");
var unity = DependencyConfiguration.Config();
var lstOfTypes = unity.Resolve<ListOfTypes>();
lstOfTypes.PrintHandlers();
Console.ReadLine();
}
Result:
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();
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");
}
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;
}
}
}
On AppEngine "Franch" and "English" as a dependency injection what do I do?
class Program
{
static void Main(string[] args)
{
IContainer container = ConfigureDependencies();
IAppEngine appEngine = container.GetInstance<IAppEngine>();
IGeeter g1 = container.GetInstance<IGeeter>("Franch");
IGeeter g2 = container.GetInstance<IGeeter>("English");
appEngine.Run();
}
private static IContainer ConfigureDependencies()
{
return new Container(x =>
{
x.For<IGeeter>().Add<FrenchGreeter>().Named("Franch");
x.For<IGeeter>().Add<EnglishGreeter>().Named("English");
x.For<IAppEngine>().Use<AppEngine>();
x.For<IGeeter>().Use<EnglishGreeter>();
x.For<IOutputDisplay>().Use<ConsoleOutputDisplay>();
});
}
}
public interface IAppEngine
{
void Run();
}
public interface IGeeter
{
string GetGreeting();
}
public interface IOutputDisplay
{
void Show(string message);
}
public class AppEngine : IAppEngine
{
private readonly IGeeter english;
private readonly IGeeter franch;
private readonly IOutputDisplay outputDisplay;
public AppEngine(IGeeter english,IGeeter franch, IOutputDisplay outputDisplay)
{
this.english = english;
this.franch = franch;
this.outputDisplay = outputDisplay;
}
public void Run()
{
outputDisplay.Show(greeter.GetGreeting());
}
}
public class EnglishGreeter : IGeeter
{
public string GetGreeting()
{
return "Hello";
}
}
public class FrenchGreeter : IGeeter
{
public string GetGreeting()
{
return "Bonjour";
}
}
As the contract for FrenchGreeter and EnglishGreeter is the same, StructureMap will not know which to use. For each wireing it uses only one instance per contract. Try something like this:
For<IGreeter>().Use<FrenchGreeter>().Named("French");
For<IGreeter>().Use<EnglishGreeter>().Named("English");
For<IAppEngine>().Use<AppEngine>()
.Ctor<IGreeter>("French").Is(x => x.TheInstanceNamed("French"))
.Ctor<IGreeter>("English").Is(x => x.TheInstanceNamed("English"));