Inline Interface implementation in Actionscript - actionscript

Is something like this possible in Actionscript?
Java:
URLFetcherFactory.setCreator(
new IURLFetcherCreator() {
public IURLFetcher create() {
return new URLFetcher();
}
}
);
Actionscript:
?
I've been wondering about this and have been unable to find anything that indicates it's possible. Figured if it was possible, I'd be able to find an answer here. Thanks! Stackoverflow rocks!

You cannot create an instance of an interface. You can, however, create a factory class:
public class URLFetcherCreator : IURLFetcherCreator {
private var _cls : Class;
public URLFetcherCreator(Class cls) {
this._cls = cls;
}
public function create() : IURLFetcher
{
return new cls();
}
}
Alternatively, change setCreator to accept a Function that returns an IURLFetcher:
URLFetcherFactory.setCreator(
function() : IURLFetcher {
return new URLFetcher();
}
);

Try this:
URLFetcherFactory.setCreator(
new IURLFetcherCreator() {
public function create():IURLFetcher {
return new URLFetcher();
}
}
);

You can't use anonymous inner classes in AS3.
For special cases like callbacks you can use Function instead of anonymous inner classes.
Java:
interface Callback {
void done(String info);
}
class Service {
void process(Callback callback);
}
...
myService.process(new Callback() {
void done(String info) {
// trace(info);
}
}
AS3:
class Service {
public function process(callback:Function):void;
}
...
myService.process(function(info:String):void {
trace(info);
});

Related

How to make override abstract method in dart or flutter

My background is from java, so i can implement abstract classes and methods in java like given bellow:
Class 1
public class Base {
public void method( VerificationCallbacks verificationCallbacks){
verificationCallbacks.signInWithEmail();
};
}
Abstract class
public abstract class VerificationCallbacks {
public abstract void signInWithEmail();
public abstract void signUpInWithEmail();
}
so we can implement these classes like
Base base = new Base();
base.method(new VerificationCallbacks() {
#Override
public void signInWithEmail() {
}
#Override
public void signUpInWithEmail() {
}
});
But now i want to implement this technique in dart or flutter
Base base = new Base();
base.method(new VerificationCallbacks());
but when i write this code to implement override methods, it shows abstract classes cannot be instantiated dart, please anyone can help me to achieve this.
class Base {
void method({
VoidCallback signInWithEmailCallback,
VoidCallback signUpWithEmailCallback,
}) {
if (true) {
signInWithEmailCallback();
} else {
signUpWithEmailCallback();
}
}
}
and
Base base = Base();
base.method(signInWithEmailCallback: () {
//
}, signUpWithEmailCallback: () {
//
});
also you can define you own alias for callback like this
typedef VerificationCallback = void Function();
and use it
class Base {
void method({
VerificationCallback signInWithEmailCallback,
VerificationCallback signUpWithEmailCallback,
}) {
// logic here
}
}

TypeInterceptor Implementation in StructureMap 4.6

Can someone help me to convert the below line of code from StructureMap 2.6 to Structure Map 4.6
public class EventAggregatorInterceptor : TypeInterceptor
{
public object Process(object target, IContext context)
{
IEventPublisher eventPublisher = context.GetInstance<IEventPublisher>();
eventPublisher.RegisterHandlers(target);
return target;
}
public bool MatchesType(Type type)
{
bool matchesType = type.ImplementsInterfaceTemplate(typeof(IEventHandler<>));
return matchesType;
}
}
I will appreciate any help
I got it working, below is the code
public class EventListenerRegistration : IInterceptorPolicy
{
public string Description
{
get
{
return "Adds the constructed object to the EventAggregator";
}
}
public IEnumerable<IInterceptor> DetermineInterceptors(Type pluginType, Instance instance)
{
if (instance.ReturnedType.FindInterfacesThatClose(typeof(IEventHandler<>)).Any())
{
Expression<Action<IContext, object>> register = (c, o) => c.GetInstance<IEventPublisher>().RegisterHandlers(o);
yield return new ActivatorInterceptor<object>(register);
}
}
}
And then I register it inside my Registry constructor
Policies.Interceptors(new EventListenerRegistration());

Implement dependency injection in background services in Xamarin Forms using Prism

I am making use of Prism in my xamarin forms project.I was able to use dependency injection(constructor injection) in my View Model without any problems.I am also making use of background services to push long running tasks in the background.How do I inject dependency in my Background services?When I try to pass the interface object as a paramater to the constructor(SyncingBackgroundingCode) ,the object(SqliteService) is null.I have registered and resolved the objects in the dependency injection container.
How to handle this case?Can anybody provide an example or link to implement this scenario?
This is the piece of code where im trying to implement dependency injection.
This is in Droid :-
public class AndroidSyncBackgroundService : Service
{
CancellationTokenSource _cts;
public override IBinder OnBind (Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand (Intent intent, StartCommandFlags flags, int startId)
{
_cts = new CancellationTokenSource ();
Task.Run (() => {
try {
//INVOKE THE SHARED CODE
var oBackground = new SyncingBackgroundingCode();
oBackground.RunBackgroundingCode(_cts.Token).Wait();
}
catch (OperationCanceledException)
{
}
finally {
if (_cts.IsCancellationRequested)
{
var message = new CancelledTask();
Device.BeginInvokeOnMainThread (
() => MessagingCenter.Send(message, "CancelledTask")
);
}
}
}, _cts.Token);
return StartCommandResult.Sticky;
}
public override void OnDestroy ()
{
if (_cts != null) {
_cts.Token.ThrowIfCancellationRequested ();
_cts.Cancel ();
}
base.OnDestroy ();
}
}
This is in PCL:-
public class SyncingBackgroundingCode
{
public SQLiteConnection _sqlconnection;
SqliteCalls oSQLite = new SqliteCalls();
ISqliteService _SqliteService;
public SyncingBackgroundingCode(ISqliteService SqliteService)
{
//object is null
}
public async Task RunBackgroundingCode(CancellationToken token)
{
DependencyService.Get<ISQLite>().GetConnection();
await Task.Run (async () => {
token.ThrowIfCancellationRequested();
if (App.oSqliteCallsMainLH != null)
{
App.bRunningBackgroundTask = true;
oSQLite = App.oSqliteCallsMainLH;
await Task.Run(async () =>
{
await Task.Delay(1);
oSQLite.ftnSaveOnlineModeXMLFormat("Offline", 0);
oSQLite.SyncEmployeeTableData();
oSQLite.SaveOfflineAppCommentData();
oSQLite.SaveOfflineAdditionToFlowData();
await Task.Delay(500);
var msgStopSyncBackgroundingTask = new StopSyncBackgroundingTask();
MessagingCenter.Send(msgStopSyncBackgroundingTask, "StopSyncBackgroundingTask");
});
}
}, token);
}
}
Unfortunately Xamarin and Xamarin Forms don't give frameworks like Prism anywhere to tie into to handle IoC scenarios. There are a couple of ways you can handle this though.
First the Container is a public property on the PrismApplication in your background service you could do something like:
public class FooBackgroundService
{
private App _app => (App)Xamarin.Forms.Application.Current;
private void DoFoo()
{
var sqlite = _app.Container.Resolve<ISQLite>();
}
}
Another slightly more involved way would be to use the ServiceLocator pattern. You might have something like the following:
public static class Locator
{
private static Func<Type, object> _resolver;
public static T ResolveService<T>() =>
(T)_resolver?.Invoke(typeof(T));
public static void SetResolver(Func<Type, object> resolver) =>
_resolver = resolver;
}
In your app you would then simply set the resolver. Prism actually does something similar to this with the ViewModel locator, which then allows it to inject the correct instance of the NavigationService.
public class App : PrismApplication
{
protected override void OnInitialized()
{
SetServiceLocator();
NavigationService.NavigateAsync("MainPage");
}
protected override void RegisterTypes()
{
// RegisterTypes
}
private void SetServiceLocator()
{
Locator.SetResolver(type => Container.Resolve(type, true));
}
}
Finally your service would simply reference the Service Locator like:
public class BarBackgroundService
{
public void DoBar()
{
var sqlite = Locator.ResolveService<ISQLite>();
// do foo
}
}

Silex passing app and request to controller classes

I want a simple way to access $app and $request in my controller classes. The document says to do this,
public function action(Application $app, Request $request) {
// Do something.
}
but it doesn't look right to have to inject $app and $request to every method. Is there a way to include $app and $request to every controller by default, maybe using the constructor? I'd like to be able to use it as $this->app.
Thanks.
In the Controllers as Services part of the documentation you can see how to inject dependencies to controller classes via the constructor - in that case a repository.
It's possible :
Create a ControllerResolver.php somewhere in your project and put this inside :
namespace MyProject;
use Silex\ControllerResolver as BaseControllerResolver;
class ControllerResolver extends BaseControllerResolver
{
protected function instantiateController($class)
{
return new $class($this->app);
}
}
Then register it in your app (before $app->run();):
$app['resolver'] = function ($app) {
return new \MyProject\ControllerResolver($app, $app['logger']);
};
Now you can create a base controller for your app, for example :
namespace MyProject;
use Silex\Application;
use Symfony\Component\HttpFoundation\Response;
abstract class BaseController
{
public $app;
public function __construct(Application $app)
{
$this->app = $app;
}
public function getParam($key)
{
$postParams = $this->app['request_stack']->getCurrentRequest()->request->all();
$getParams = $this->app['request_stack']->getCurrentRequest()->query->all();
if (isset($postParams[$key])) {
return $postParams[$key];
} elseif (isset($getParams[$key])) {
return $getParams[$key];
} else {
return null;
}
}
public function render($view, array $parameters = array())
{
$response = new Response();
return $response->setContent($this->app['twig']->render($view, $parameters));
}
}
And extend it :
class HomeController extends BaseController
{
public function indexAction()
{
// now you can use $this->app
return $this->render('home.html.twig');
}
}

Use ConstructedBy together with the non-generic For

I have this registration in StructureMap
ObjectFactory.Initialize(x => {
x.For<IPageModel>().UseSpecial(y => y.ConstructedBy( r => ((MvcHandler) HttpContext.Current.Handler).RequestContext.RouteData.GetCurrentModel<IPageModel>()));
});
And then I access this object in my constructor like this
public HomeController(IPageModel model) {}
Now I would like to register all concrete types that implements the interface IPageModel and when asked for I want to use the same For<> statement to get the correct instance.
It seems like i could use Scan together with my own convention to do this but I can't figure out exactly how to do it.
This is some example code
x.Scan(scanner =>
{
scanner.AssembliesFromApplicationBaseDirectory();
scanner.Convention<MySpecialConvetion>();
});
public class MySpecialConvetion : IRegistrationConvention {
public void Process(Type type, Registry registry) {
if(type.IsAssignableFrom(typeof(IPageModel))) {
registry.For<CONCRETE IMPLEMENTATION>().UseSpecial(y => y.ConstructedBy( r => ((MvcHandler) HttpContext.Current.Handler).RequestContext.RouteData.GetCurrentModel<CONCRETE IMPLEMENTATION>()));
}
}
}
Edit: It seems like I need to use the non-generic For, but how can I handle the construction my self using the non-generic For?
I got this working by creating a generic method definition, and used reflection to populate the types. Easier to show than explain:
public class MySpecialConvetion : IRegistrationConvention
{
public static readonly MethodInfo RegisterMethod = typeof (MySpecialConvetion)
.GetMethod("Register", BindingFlags.NonPublic | BindingFlags.Static)
.GetGenericMethodDefinition();
public void Process(Type type, Registry registry)
{
if (type.IsAssignableFrom(typeof (IPageModel)))
{
var specificRegisterMethod = RegisterMethod.MakeGenericMethod(new[] { type });
specificRegisterMethod.Invoke(null, new object[] { registry });
}
}
static private void Register<T>(Registry registry)
where T : IPageModel
{
registry
.For<T>()
.UseSpecial(y => y.ConstructedBy(r => GetCurrentPageModel<T>()));
}
static private T GetCurrentPageModel<T>()
where T : IPageModel
{
var handler = (MvcHandler) HttpContext.Current.Handler;
if (handler == null)
return default(T);
return handler.RequestContext.RouteData.GetCurrentModel<T>();
}
}
I added an intermediate step and checked for a null handler since I didn't have one in my site. But this should get you the missing piece you needed.

Resources