i have a class that binds a obj-c object
public unsafe partial class CUSTOMER_INFO : NSObject {
[Export ("signature", ArgumentSemantic.Retain)]
get {
NSData ret;
if (IsDirectBinding) {
ret = Runtime.GetNSObject<NSData> (global::ApiDefinition.Messaging.IntPtr_objc_msgSend (this.Handle, Selector.GetHandle ("signature")));
} else {
ret = Runtime.GetNSObject<NSData> (global::ApiDefinition.Messaging.IntPtr_objc_msgSendSuper (this.SuperHandle, Selector.GetHandle ("signature")));
}
if (!IsNewRefcountEnabled ())
__mt_Signature_var = ret;
return ret;
}
[Export ("setSignature:", ArgumentSemantic.Retain)]
set {
if (value == null)
throw new ArgumentNullException ("value");
if (IsDirectBinding) {
global::ApiDefinition.Messaging.void_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle ("setSignature:"), value.Handle);
} else {
global::ApiDefinition.Messaging.void_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("setSignature:"), value.Handle);
}
if (!IsNewRefcountEnabled ())
__mt_Signature_var = value;
}
}
but when i declare it and i pass it to a method (inside a ios binding library), i get the known exception
System.ExecutionEngineException: Attempting to JIT compile method
'CUSTOMER_INFO:set_Signature (Foundation.NSData)' while running with
--aot-only. See http://docs.xamarin.com/ios/about/limitations for more information.
UPDATE after suggestion by user #SushiHangover
In my iOS binding library project in generated code I tried this workaround:
[Register("CUSTOMER_INFO", true)]
//public unsafe partial class CUSTOMER_INFO : NSObject {
public unsafe partial class CUSTOMER_INFO_GENERIC<T> : NSObject where T : NSObject
{
[CompilerGenerated]
static readonly IntPtr class_ptr = Class.GetHandle ("CUSTOMER_INFO");
public override IntPtr ClassHandle { get { return class_ptr; } }
[CompilerGenerated]
[EditorBrowsable (EditorBrowsableState.Advanced)]
[Export ("init")]
public CUSTOMER_INFO_GENERIC () : base (NSObjectFlag.Empty)
{
IsDirectBinding = GetType ().Assembly == global::ApiDefinition.Messaging.this_assembly;
if (IsDirectBinding) {
InitializeHandle (global::ApiDefinition.Messaging.IntPtr_objc_msgSend (this.Handle, global::ObjCRuntime.Selector.GetHandle ("init")), "init");
} else {
InitializeHandle (global::ApiDefinition.Messaging.IntPtr_objc_msgSendSuper (this.SuperHandle, global::ObjCRuntime.Selector.GetHandle ("init")), "init");
}
}
[CompilerGenerated]
[EditorBrowsable (EditorBrowsableState.Advanced)]
protected CUSTOMER_INFO_GENERIC(NSObjectFlag t) : base (t)
{
IsDirectBinding = GetType ().Assembly == global::ApiDefinition.Messaging.this_assembly;
}
[CompilerGenerated]
[EditorBrowsable (EditorBrowsableState.Advanced)]
protected internal CUSTOMER_INFO_GENERIC(IntPtr handle) : base (handle)
{
IsDirectBinding = GetType ().Assembly == global::ApiDefinition.Messaging.this_assembly;
}
// other methods....
// .................
[CompilerGenerated]
object __mt_Signature_var;
[CompilerGenerated]
public virtual NSData SignatureNoJit {
[Export ("signature", ArgumentSemantic.Retain)]
get {
NSData ret;
if (IsDirectBinding) {
ret = Runtime.GetNSObject<NSData> (global::ApiDefinition.Messaging.IntPtr_objc_msgSend (this.Handle, Selector.GetHandle ("signature")));
} else {
ret = Runtime.GetNSObject<NSData> (global::ApiDefinition.Messaging.IntPtr_objc_msgSendSuper (this.SuperHandle, Selector.GetHandle ("signature")));
}
if (!IsNewRefcountEnabled ())
__mt_Signature_var = ret;
return ret;
}
[Export ("setSignature:", ArgumentSemantic.Retain)]
set {
if (value == null)
throw new ArgumentNullException ("value");
if (IsDirectBinding) {
global::ApiDefinition.Messaging.void_objc_msgSend_IntPtr (this.Handle, Selector.GetHandle ("setSignature:"), value.Handle);
} else {
global::ApiDefinition.Messaging.void_objc_msgSendSuper_IntPtr (this.SuperHandle, Selector.GetHandle ("setSignature:"), value.Handle);
}
if (!IsNewRefcountEnabled ())
__mt_Signature_var = value;
}
}
[CompilerGenerated]
protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
if (Handle == IntPtr.Zero) {
__mt_Signature_var = null;
}
}
}
public class CUSTOMER_INFO_NOJIT : CUSTOMER_INFO_GENERIC<NSData>
{
// A specialized subclass and this is passed to your ObjC-based method
}
But when i call
NSData tmp = NSData.FromArray(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF });
CUSTOMER_INFO_NOJIT CustomerInfo = new CUSTOMER_INFO_NOJIT();
CustomerInfo.CardHolderEmail = CardHolderEMail;
CustomerInfo.CardHolderMobile = CardHolderMobilePhone;
CustomerInfo.SignatureNoJit = tmp;
I get this exception again:
System.ExecutionEngineException: Attempting to JIT compile method
'CUSTOMER_INFO_GENERIC`1:set_SignatureNoJit
(Foundation.NSData)' while running with --aot-only. See
http://docs.xamarin.com/ios/about/limitations for more information.
Anybody can suggest me a workaround/pattern to avoid this exception?
Thank you!
Lewix
(I might need more coffee...so take this with grain of salt... :-)
This:
public unsafe partial class CUSTOMER_INFO : NSObject {
~~~~
}
Becomes:
public unsafe partial class CUSTOMER_INFO_GENERIC<T> : NSObject where T : NSObject {
~~~~
}
class CUSTOMER_INFO : CUSTOMER_INFO_GENERIC<NSData>
{
// A specialized subclass and this is passed to your ObjC-based method
}
And thus this in your set and the get return can be resolved as NSData vs. NSObject and no jitting is required and the compiler created/resolved the classes...
Related
I have an example that works in dart before null safety that doesn't after upgrading to Null safety. I can't figure out what's going on.
It gives me the error
A value of type 'dynamic Function()?' can't be returned from the method 'doSomething' because it has a return type of 'dynamic Function()'
But I didn't define anything as Nullable.
typedef RandomFunction = Function();
class RegisteredFunctions {
Map<String, RandomFunction> types = {};
static final RegisteredFunctions _registry = RegisteredFunctions._init();
RegisteredFunctions._init() {}
factory RegisteredFunctions() {
return _registry;
}
void registerFunction(String name, RandomFunction func) {
types[name] = func;
}
RandomFunction doSomething(String id) => types[id]; //<---- gives error
}
void doStuff(){
print('Doing Something');
}
void main() {
RegisteredFunctions functions = RegisteredFunctions();
functions.registerFunction('func1', doStuff);
functions.doSomething('func1')();
}
For anyone else trying to figure it out.. this fixed it.
typedef RandomFunction = Object? Function();
class RegisteredFunctions {
Map<String, RandomFunction> types = {};
static final RegisteredFunctions _registry = RegisteredFunctions._init();
RegisteredFunctions._init() {}
factory RegisteredFunctions() {
return _registry;
}
void registerFunction(String name, RandomFunction func) {
types[name] = func;
}
// RandomFunction doSomething(String id) => types[id]; // <----- Doesn't work
// RandomFunction doSomething(String id) => types[id]!; // <----- Works
RandomFunction doSomething(String id) { // <----- Works better
RandomFunction? func = types[id];
if (func != null) {
return func;
} else {
return (){};
}
}
}
void doStuff(){
print('Doing Something');
}
void doOtherStuff(){
print('Doing Something else');
}
void main() {
RegisteredFunctions functions = RegisteredFunctions();
functions.registerFunction('func1', doStuff);
functions.registerFunction('func2', doOtherStuff);
functions.doSomething('func1')();
functions.doSomething('func2')();
}
I am new to F#. As a learning experiment, I am rewriting a C# application in pure F#. How can the "RelayCommand" , RelayCommand, of C# be written in F# ?
Any help is most appreciated.
TIA
As requested, this is the RelayCommand I've been using in C#. :( It seems overly complicated. (There must surely be a simpler one!).
public class RelayCommand<T> : ICommand
{
private readonly WeakAction<T> _execute;
private readonly WeakFunc<T, bool> _canExecute;
public RelayCommand(Action<T> execute)
: this(execute, null)
{
}
public RelayCommand(Action<T> execute, Func<T, bool> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
_execute = new WeakAction<T>(execute);
if (canExecute != null)
{
_canExecute = new WeakFunc<T, bool>(canExecute);
}
}
public event EventHandler CanExecuteChanged
{
add
{
if (_canExecute != null)
{
CommandManager.RequerySuggested += value;
}
}
remove
{
if (_canExecute != null)
{
CommandManager.RequerySuggested -= value;
}
}
}
public void RaiseCanExecuteChanged()
{
CommandManager.InvalidateRequerySuggested();
}
public bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
if (_canExecute.IsStatic || _canExecute.IsAlive)
{
if (parameter == null && typeof(T).IsValueType)
{
return _canExecute.Execute(default(T));
}
if (parameter == null || parameter is T)
{
return (_canExecute.Execute((T)parameter));
}
}
return false;
}
public virtual void Execute(object parameter)
{
var val = parameter;
if (CanExecute(val)
&& _execute != null
&& (_execute.IsStatic || _execute.IsAlive))
{
if (val == null)
{
if (typeof(T).IsValueType)
{
_execute.Execute(default(T));
}
else
{
// ReSharper disable ExpressionIsAlwaysNull
_execute.Execute((T)val);
// ReSharper restore ExpressionIsAlwaysNull
}
}
else
{
_execute.Execute((T)val);
}
}
}
}
public class WeakFunc<TResult>
{
private Func<TResult> _staticFunc;
/// <summary>
/// Gets or sets the <see cref="MethodInfo" /> corresponding to this WeakFunc's
/// method passed in the constructor.
/// </summary>
protected MethodInfo Method
{
get;
set;
}
/// <summary>
/// Get a value indicating whether the WeakFunc is static or not.
/// </summary>
public bool IsStatic
{
get
{
return _staticFunc != null;
}
}
public virtual string MethodName
{
get
{
if (_staticFunc != null)
{
return _staticFunc.Method.Name;
}
return Method.Name;
}
}
protected WeakReference FuncReference
{
get;
set;
}
protected WeakReference Reference
{
get;
set;
}
protected WeakFunc()
{
}
public WeakFunc(Func<TResult> func)
: this(target: func?.Target, func: func)
{
}
public WeakFunc(object target, Func<TResult> func)
{
if (func.Method.IsStatic)
{
_staticFunc = func;
if (target != null)
{
// Keep a reference to the target to control the
// WeakAction's lifetime.
Reference = new WeakReference(target);
}
return;
}
Method = func.Method;
FuncReference = new WeakReference(func.Target);
Reference = new WeakReference(target);
}
public virtual bool IsAlive
{
get
{
if (_staticFunc == null
&& Reference == null)
{
return false;
}
if (_staticFunc != null)
{
if (Reference != null)
{
return Reference.IsAlive;
}
return true;
}
return Reference.IsAlive;
}
}
public object Target
{
get
{
if (Reference == null)
{
return null;
}
return Reference.Target;
}
}
protected object FuncTarget
{
get
{
if (FuncReference == null)
{
return null;
}
return FuncReference.Target;
}
}
public TResult Execute()
{
if (_staticFunc != null)
{
return _staticFunc();
}
var funcTarget = FuncTarget;
if (IsAlive)
{
if (Method != null
&& FuncReference != null
&& funcTarget != null)
{
return (TResult)Method.Invoke(funcTarget, null);
}
}
return default(TResult);
}
public void MarkForDeletion()
{
Reference = null;
FuncReference = null;
Method = null;
_staticFunc = null;
}
}
As a newbie to F#, how can this be implemented? How does F# deal with "WeakAction"?
Thank you.
I have one question. I am using neo4j-ogm snapshot 1.5 .
I have the following classes:
#NodeEntity
public abstract class Entity {
#GraphId
protected Long id;
#Expose
protected String code = null;
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || id == null || getClass() != o.getClass())
return false;
Entity entity = (Entity) o;
if (!id.equals(entity.id))
return false;
return true;
}
#Override
public int hashCode() {
return (id == null) ? -1 : id.hashCode();
}
public Long getId(){
return id;
}
public void setId(Long neo4jId){
this.id = neo4jId;
}
public String getCode(){
return code;
}
public void setCode(String code){
this.code = code;
}
}
public class PropertyGroup extends Entity{
#Expose
private String name;
public PropertyGroup(){
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class User extends Entity {
private Long registration_date;
private Long last_login_date;
private Boolean is_admin = false;
private String push_dev;
private String push_id;
private Boolean push_enabled = false;
#Expose
private String avatar;
#Expose
private String avatarUrl;
#Expose
private String name;
#Expose
private volatile String password;
#Expose
private int likes = 0;
#Expose
private int questionCount = 0;
#Expose
private int followersCount = 0;
#Expose
private boolean isFollowing = false;
// public Set<UserPropertyRelation> properties;
// #Relationship(type = ModelRelType.ANSWERED)
// public Set<UserAnsweredRelation> userAnswers;
//
// #Relationship(type = ModelRelType.LIKES)
// private Set<LikesQuestionRelation> questionsLiked;
#Expose
#Relationship(type = ModelRelType.HAS_PROPERTY)
private Set<PropertyGroup> properties;
// private Profile userProfile;
// private List<Fact> facts;
// #Expose
// #Relationship(type = ModelRelType.OWNS)
// private List<Question> questions;
public User(){
// this.properties = new LinkedHashSet<UserPropertyRelation>();
// this.userAnswers = new LinkedHashSet<UserAnsweredRelation>();
// this.userProperties = new HashSet<PropertyGroup>();
// this.setFacts(new ArrayList<Fact>());
this.properties = new HashSet<PropertyGroup>();
}
public User(long regDate, long lastLoginDate, boolean isAdmin,
String pushDev, String pushId, boolean pushEnabled){
this();
this.registration_date = regDate;
this.last_login_date = lastLoginDate;
this.is_admin = isAdmin;
this.push_dev = pushDev;
this.push_id = pushId;
this.push_enabled = pushEnabled;
}
// public void addUserAnsweredRelation(UserAnsweredRelation answer){
// answer.setStartNode(this);
// this.userAnswers.add(answer);
// }
//
// public Set<UserAnsweredRelation> getUserAnsweredRelations() {
// return this.userAnswers;
// }
// public void setUserAnsweredRelations(Set<UserAnsweredRelation> userAnswers){
// for(UserAnsweredRelation a : userAnswers){
// a.setStartNode(this);
// }
//
// this.userAnswers = userAnswers;
// }
//
// public void addUserPropertyRelation(UserPropertyRelation rel){
// rel.setUser(this);
// properties.add(rel);
// }
//
// public void setUserPropertyRelations(Set<UserPropertyRelation> properties){
// for(UserPropertyRelation r: properties){
// r.setUser(this);
// }
//
// this.properties = properties;
// }
// public Set<UserPropertyRelation> getUserPropertyRelations(){
// return this.properties;
// }
public long getRegistrationDate() {
return registration_date;
}
public void setRegistrationDate(long registrationDate) {
this.registration_date = registrationDate;
}
public long getLastLoginDate() {
return last_login_date;
}
public void setLastLoginDate(long lastLoginDate) {
this.last_login_date = lastLoginDate;
}
public boolean isAdmin() {
return is_admin;
}
public void setAdmin(boolean isAdmin) {
this.is_admin = isAdmin;
}
public String getPushDev() {
return push_dev;
}
public void setPushDev(String pushDev) {
this.push_dev = pushDev;
}
public String getPushId() {
return push_id;
}
public void setPushId(String pushId) {
this.push_id = pushId;
}
public boolean isPushEnabled() {
return push_enabled;
}
public void setPushEnabled(boolean pushEnabled) {
this.push_enabled = pushEnabled;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<PropertyGroup> getProperties() {
return properties;
}
public void setProperties(Set<PropertyGroup> properties) {
this.properties = properties;
}
// public Profile getUserProfile() {
// return userProfile;
// }
//
// public void setUserProfile(Profile userProfile) {
// this.userProfile = userProfile;
// }
// public Set<LikesQuestionRelation> getQuestionsLiked() {
// return questionsLiked;
// }
//
// public void setQuestionsLiked(Set<LikesQuestionRelation> likes) {
// this.questionsLiked = likes;
// }
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
// public List<Fact> getFacts() {
// return facts;
// }
//
// public void setFacts(List<Fact> facts) {
// this.facts = facts;
// }
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
public int getLikes() {
return likes;
}
public void setLikes(int likes) {
this.likes = likes;
}
public int getQuestionCount() {
return questionCount;
}
public void setQuestionCount(int questionCount) {
this.questionCount = questionCount;
}
public int getFollowersCount() {
return followersCount;
}
public void setFollowersCount(int followersCount) {
this.followersCount = followersCount;
}
public boolean isFollowing() {
return isFollowing;
}
public void setFollowing(boolean isFollowing) {
this.isFollowing = isFollowing;
}
// public List<Question> getQuestions() {
// return questions;
// }
//
// public void setQuestions(List<Question> questions) {
// this.questions = questions;
// }
When I am trying to do the following:
SessionFactory sessionFactory = new SessionFactory(modelsPackageName);
Session session = sessionFactory.openSession(url);
String cypher = "MATCH (u:User {code: {CODE}})-[h:HAS_PROPERTY]->(pg:PropertyGroup) " +
"RETURN u, h, pg";
Map<String, Object> params = new HashMap<String, Object>();
params.put("CODE", "fc48b19ba6f8427a03d6e5990bcef99a28f55592b80fe38731cf805ed188cabf");
// System.out.println(Util.mergeParamsWithCypher(cypher, params));
User u = session.queryForObject(User.class, cypher, params);
The user Object (u) never contains any properties (PropertyGroup entity is not mapped).
What am I doing wrong?
Any help would be appreciated.
Regards,
Alex
If you're using queryForObject return just one column- the object, in your case u.
Neo4j OGM 1.x does not support mapping of custom query results to domain entities, so you will have to return the entity ID, and then do an additional load-by-id specifying a custom depth.
OGM 2.0 (currently 2.0.0-M01) does support mapping custom query results to entities. Your query will remain the same (i.e. return u,h,pg) but instead you'll use the query() method that returns a Result. From the result, you'll be able to get your User entity by column-name u and it'll be hydrated with the PropertyGroups it is related to.
Update:
The dependencies for OGM 2.0.0-M01 are
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-ogm-api</artifactId>
<version>2.0.0-M01</version>
</dependency>
<dependency>
<groupId>org.neo4j</groupId>
<artifactId>neo4j-ogm-core</artifactId>
<version>2.0.0-M01</version>
</dependency>
Be sure to read the about the configuration changes since you're upgrading from OGM 1.x http://neo4j.com/docs/ogm/java/2.0.0-M01/#reference_setup
A summary of new features: http://neo4j.com/blog/neo4j-ogm-2-0-milestone-1/
I'm needing to collect information from internet data usage on the iphone, the below code in C # I'm using only returns 0 values.
I'm using the right class?
have some reference I need to add in Xamarin?
appears in mono 3 types of classes, Coincidentally the "MacOsIPv4InterfaceStatistics" interface always returns the fixed value 0.
https://github.com/mono/mono/blob/master/mcs/class/System/System.Net.NetworkInformation/IPv4InterfaceStatistics.cs
Win32IPv4InterfaceStatistics
LinuxIPv4InterfaceStatistics
MacOsIPv4InterfaceStatistics
using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Threading;
using MonoTouch.ObjCRuntime;
namespace Taximetro { public delegate void Update();
public static class ControleUso
{
public static long controller;
public static long BytesReceivedWiFi;
public static long BytesSentWiFi;
public static long BytesReceived3G;
public static long BytesSent3G;
public static Update UpdateMethod;
public static void DoWork()
{
foreach (var netint in NetworkInterface.GetAllNetworkInterfaces()) {
var stats = netint.GetIPv4Statistics ();
//WiFi
//if (netint.Name.StartsWith ("en")) {
BytesReceivedWiFi += stats.BytesReceived;
BytesSentWiFi += stats.BytesSent;
//}
//3G
if (netint.Name.StartsWith ("pdp_ip")) {
BytesReceived3G += stats.BytesReceived;
BytesSent3G += stats.BytesSent;
}
}
controller++;
if (UpdateMethod != null) {
UpdateMethod ();
}
Thread.Sleep (1000);
}
}
}
Notice that data is uint and not long, which means it will overflow every 4GB of data.
Edit: After some Googling around I noticed that this data is reset on iOS reboot. Just some heads ups to anyone who might use this.
public enum InterfaceTypes
{
Wifi,
Cellular
}
public class DataUsage
{
[DllImport ("libc")]
static extern int getifaddrs (out IntPtr ifap);
[DllImport ("libc")]
static extern void freeifaddrs (IntPtr ifap);
const int AF_LINK = 18;
struct ifaddrs
{
public IntPtr ifa_next;
public string ifa_name;
public uint ifa_flags;
public IntPtr ifa_addr;
public IntPtr ifa_netmask;
public IntPtr ifa_dstaddr;
public IntPtr ifa_data;
}
public InterfaceTypes InterfaceType {
get;
private set;
}
public uint BytesSent {
get;
private set;
}
public uint BytesReceived {
get;
private set;
}
public static List<DataUsage> GetAllNetworkInterfacesUsage ()
{
IntPtr ifap;
if (getifaddrs (out ifap) != 0)
throw new SystemException ("getifaddrs() failed");
List<DataUsage> usages = new List<DataUsage> ();
try {
IntPtr next = ifap;
while (next != IntPtr.Zero) {
ifaddrs addr = (ifaddrs)Marshal.PtrToStructure (next, typeof(ifaddrs));
next = addr.ifa_next;
string name = addr.ifa_name;
if (addr.ifa_addr != IntPtr.Zero) {
if (Marshal.ReadByte (addr.ifa_addr, 1) == AF_LINK) {
if (!name.StartsWith ("en") && !name.StartsWith ("pdp_ip"))
continue;
usages.Add (new DataUsage () {
InterfaceType = name.StartsWith ("en") ? InterfaceTypes.Wifi : InterfaceTypes.Cellular,
BytesReceived = (uint)Marshal.ReadInt32 (addr.ifa_data, 40),
BytesSent = (uint)Marshal.ReadInt32 (addr.ifa_data, 44)
});
}
}
}
} finally {
freeifaddrs (ifap);
}
return usages;
}
}
Below is my code, and the issue is that the dispose method of my UnitOfWork class does not get called. For DI, I am using Unity v2.1.505 with Unity.Mvc3 v1.2 in Asp.net MVC3 Application
[assembly: PreApplicationStartMethod(typeof(Program), "Initialize")]
namespace Practice.DependencyResolution.Concrete
{
public class Program
{
private static IUnityContainer container;
public static void Initialize()
{
if (container == null) container = new UnityContainer();
string databaseSource = Settings.Default.DatabaseSource;
var dependencyMapperType = Type.GetType("Practice.DependencyResolution.Concrete." + databaseSource + "DependencyMapper", true);
var dependencyMapper = (IDependencyMapper)Activator.CreateInstance(dependencyMapperType);
var dependencyMapperContext = new DependencyMapperContext(dependencyMapper);
dependencyMapperContext.MapDependencies(container);
ControllerBuilder.Current.SetControllerFactory(new UnityControllerFactory(container));
var locator = new UnityServiceLocator(container);
ServiceLocator.SetLocatorProvider(() => locator);
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
}
}
}
internal class DependencyMapperContext
{
private IDependencyMapper dependencyMapper;
public DependencyMapperContext(IDependencyMapper dependencyMapper)
{
this.dependencyMapper = dependencyMapper;
}
public void MapDependencies(IUnityContainer container)
{
dependencyMapper.MapDependencies(container);
}
}
internal class AnyDependencyMapper : IDependencyMapper
{
public void MapDependencies(IUnityContainer container)
{
container.RegisterType<ISupplierRepository, SupplierRepository>();
container.RegisterType<IUnitOfWork, UnitOfWork>(new HierarchicalLifetimeManager());
}
}
public class UnitOfWork : IUnitOfWork
{
private readonly TransactionScope transactionScope;
private readonly ModelDataContext context;
private bool disposed = false;
public UnitOfWork()
{
transactionScope = new TransactionScope();
this.context = new ModelDataContext();
}
ModelDataContext IUnitOfWork.Context
{
get
{
Debug.WriteLine("context get called");
return context;
}
}
public void Commit()
{
if (disposed) throw new ObjectDisposedException("transactionScope");
transactionScope.Complete();
}
protected virtual void Dispose(bool disposing)
{
if (disposed == false)
{
if (disposing)
{
if (context != null)
{
context.Dispose();
}
if (transactionScope != null)
{
transactionScope.Dispose();
}
disposed = true;
}
}
}
public void Dispose()
{
Debug.WriteLine("Access dispose called");
if (HttpContext.Current != null && HttpContext.Current.Error != null)
{
//transaction transactionScope will be disposed automatically, do nothing
}
else
{
Commit();
}
Dispose(true);
GC.SuppressFinalize(this);
}
}
public class SupplierRepository : ISupplierRepository
{
private readonly IUnitOfWork unitOfWork;
private bool disposed = false;
public SupplierRepository(IUnitOfWork unitOfWork)
{
this.unitOfWork = unitOfWork;
}
public IList<SupplierItem> GetAll()
{
return unitOfWork.Context.SupplierItems.ToList();
}
public SupplierItem GetById(object id)
{
return unitOfWork.Context.SupplierItems.SingleOrDefault(a => a.SupplierID == (int)id);
}
public void Insert(SupplierItem entity)
{
unitOfWork.Context.SupplierItems.InsertOnSubmit(entity);
unitOfWork.Context.SubmitChanges();
}
public void Delete(object id)
{
var supplier = unitOfWork.Context.SupplierItems.SingleOrDefault(a => a.SupplierID == (int)id);
unitOfWork.Context.SupplierItems.DeleteOnSubmit(supplier);
unitOfWork.Context.SubmitChanges();
}
public void Delete(SupplierItem entityToDelete)
{
Delete(entityToDelete.SupplierID);
}
public void Update(SupplierItem entityToUpdate)
{
var supplier = unitOfWork.Context.SupplierItems.SingleOrDefault(a => a.SupplierID == entityToUpdate.SupplierID);
supplier.Address = entityToUpdate.Address;
supplier.City = entityToUpdate.City;
supplier.CompanyName = entityToUpdate.CompanyName;
supplier.ContactName = entityToUpdate.ContactName;
supplier.ContactTitle = entityToUpdate.ContactTitle;
supplier.Country = entityToUpdate.Country;
supplier.Fax = entityToUpdate.Fax;
supplier.HomePage = entityToUpdate.HomePage;
supplier.Phone = entityToUpdate.Phone;
supplier.PostalCode = entityToUpdate.PostalCode;
supplier.Region = entityToUpdate.Region;
unitOfWork.Context.SubmitChanges();
}
public SupplierItem GetDefault()
{
return new SupplierItem();
}
}
I am new to DI and Unity, thanks in advance.
I do read that you are using MVC 3. Nevertheless, if there is a possibility for you to update to MVC 4, then the new Unity 3 has support for MVC out of the box, and works with the HierarchicalLifetimeManager.
I am not familiar with the Unity.Mvc3 NuGet package (which is not supported by Microsoft) though.